Revert "s4:password_hash LDB module - don't break the provision"
[metze/samba/wip.git] / source4 / dsdb / samdb / ldb_modules / password_hash.c
index 2dddb26550fbbc60a5ceeae7e40a6f331e10d4c5..f9e7f52cd95b8015cecf0f184271f875eb6d9c30 100644 (file)
@@ -1,10 +1,11 @@
 /* 
    ldb database module
 
-   Copyright (C) Simo Sorce  2004-2006
+   Copyright (C) Simo Sorce  2004-2008
    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005-2006
    Copyright (C) Andrew Tridgell 2004
-   Copyright (C) Stefan Metzmacher 2007
+   Copyright (C) Stefan Metzmacher 2007-2010
+   Copyright (C) Matthias Dieter Wallnöfer 2009-2010
 
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
@@ -25,7 +26,7 @@
  *
  *  Component: ldb password_hash module
  *
- *  Description: correctly update hash values based on changes to userPassword and friends
+ *  Description: correctly handle AD password changes fields
  *
  *  Author: Andrew Bartlett
  *  Author: Stefan Metzmacher
@@ -33,9 +34,7 @@
 
 #include "includes.h"
 #include "libcli/ldap/ldap_ndr.h"
-#include "ldb/include/ldb_errors.h"
-#include "ldb/include/ldb.h"
-#include "ldb/include/ldb_private.h"
+#include "ldb_module.h"
 #include "librpc/gen_ndr/misc.h"
 #include "librpc/gen_ndr/samr.h"
 #include "libcli/auth/libcli_auth.h"
 #include "auth/kerberos/kerberos.h"
 #include "system/time.h"
 #include "dsdb/samdb/samdb.h"
-#include "dsdb/common/flags.h"
+#include "../libds/common/flags.h"
 #include "dsdb/samdb/ldb_modules/password_modules.h"
 #include "librpc/ndr/libndr.h"
 #include "librpc/gen_ndr/ndr_drsblobs.h"
-#include "lib/crypto/crypto.h"
+#include "../lib/crypto/crypto.h"
 #include "param/param.h"
 
-/* If we have decided there is reason to work on this request, then
+/* If we have decided there is reason to work on this request, then
  * setup all the password hash types correctly.
  *
- * If the administrator doesn't want the userPassword stored (set in the
- * domain and per-account policies) then we must strip that out before
- * we do the first operation.
+ * If we haven't the hashes yet but the password given as plain-text (attributes
+ * 'unicodePwd', 'userPassword' and 'clearTextPassword') we have to check for
+ * the constraints. Once this is done, we calculate the password hashes.
  *
- * Once this is done (which could update anything at all), we
- * calculate the password hashes.
+ * Notice: unlike the real AD which only supports the UTF16 special based
+ * 'unicodePwd' and the UTF8 based 'userPassword' plaintext attribute we
+ * understand also a UTF16 based 'clearTextPassword' one.
+ * The latter is also accessible through LDAP so it can also be set by external
+ * tools and scripts. But be aware that this isn't portable on non SAMBA 4 ADs!
  *
- * This function must not only update the unicodePwd, dBCSPwd and
- * supplementalCredentials fields, it must also atomicly increment the
- * msDS-KeyVersionNumber.  We should be in a transaction, so all this
- * should be quite safe...
+ * Also when the module receives only the password hashes (possible through
+ * specifying an internal LDB control - for security reasons) some checks are
+ * performed depending on the operation mode (see below) (e.g. if the password
+ * has been in use before if the password memory policy was activated).
+ *
+ * Attention: There is a difference between "modify" and "reset" operations
+ * (see MS-ADTS 3.1.1.3.1.5). If the client sends a "add" and "remove"
+ * operation for a password attribute we thread this as a "modify"; if it sends
+ * only a "replace" one we have an (administrative) reset.
  *
  * Finally, if the administrator has requested that a password history
  * be maintained, then this should also be written out.
  *
  */
 
-struct ph_context {
+/* TODO: [consider always MS-ADTS 3.1.1.3.1.5]
+ * - Check for right connection encryption
+ */
 
-       enum ph_type {PH_ADD, PH_MOD} type;
-       enum ph_step {PH_ADD_SEARCH_DOM, PH_ADD_DO_ADD, PH_MOD_DO_REQ, PH_MOD_SEARCH_SELF, PH_MOD_SEARCH_DOM, PH_MOD_DO_MOD} step;
+/* Notice: Definition of "dsdb_control_password_change_status" moved into
+ * "samdb.h" */
 
+struct ph_context {
        struct ldb_module *module;
-       struct ldb_request *orig_req;
+       struct ldb_request *req;
 
        struct ldb_request *dom_req;
        struct ldb_reply *dom_res;
 
-       struct ldb_request *down_req;
-
-       struct ldb_request *search_req;
        struct ldb_reply *search_res;
 
-       struct ldb_request *mod_req;
+       struct dsdb_control_password_change_status *status;
 
-       struct dom_sid *domain_sid;
-};
+       bool pwd_reset;
 
-struct domain_data {
-       bool store_cleartext;
-       uint_t pwdProperties;
-       uint_t pwdHistoryLength;
-       char *netbios_domain;
-       char *dns_domain;
-       char *realm;
+       bool change_status;
+       bool hash_values;
+       bool change_old_pw_checked;
 };
 
+
 struct setup_password_fields_io {
        struct ph_context *ac;
-       struct domain_data *domain;
+
        struct smb_krb5_context *smb_krb5_context;
 
        /* infos about the user account */
        struct {
-               uint32_t user_account_control;
+               uint32_t userAccountControl;
+               NTTIME pwdLastSet;
                const char *sAMAccountName;
                const char *user_principal_name;
                bool is_computer;
+               uint32_t restrictions;
        } u;
 
-       /* new credentials */
-       struct {
-               const char *cleartext;
+       /* new credentials and old given credentials */
+       struct setup_password_fields_given {
+               const struct ldb_val *cleartext_utf8;
+               const struct ldb_val *cleartext_utf16;
                struct samr_Password *nt_hash;
                struct samr_Password *lm_hash;
-       } n;
+       } n, og;
 
        /* old credentials */
        struct {
+               struct samr_Password *nt_hash;
+               struct samr_Password *lm_hash;
                uint32_t nt_history_len;
                struct samr_Password *nt_history;
                uint32_t lm_history_len;
                struct samr_Password *lm_history;
                const struct ldb_val *supplemental;
                struct supplementalCredentialsBlob scb;
-               uint32_t kvno;
        } o;
 
        /* generated credentials */
@@ -140,32 +147,42 @@ struct setup_password_fields_io {
                struct samr_Password *nt_history;
                uint32_t lm_history_len;
                struct samr_Password *lm_history;
+               const char *salt;
+               DATA_BLOB aes_256;
+               DATA_BLOB aes_128;
+               DATA_BLOB des_md5;
+               DATA_BLOB des_crc;
                struct ldb_val supplemental;
                NTTIME last_set;
-               uint32_t kvno;
        } g;
 };
 
+/* Get the NT hash, and fill it in as an entry in the password history, 
+   and specify it into io->g.nt_hash */
+
 static int setup_nt_fields(struct setup_password_fields_io *io)
 {
+       struct ldb_context *ldb;
        uint32_t i;
 
        io->g.nt_hash = io->n.nt_hash;
+       ldb = ldb_module_get_ctx(io->ac->module);
 
-       if (io->domain->pwdHistoryLength == 0) {
+       if (io->ac->status->domain_data.pwdHistoryLength == 0) {
                return LDB_SUCCESS;
        }
 
        /* We might not have an old NT password */
        io->g.nt_history = talloc_array(io->ac,
                                        struct samr_Password,
-                                       io->domain->pwdHistoryLength);
+                                       io->ac->status->domain_data.pwdHistoryLength);
        if (!io->g.nt_history) {
-               ldb_oom(io->ac->module->ldb);
+               ldb_oom(ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       for (i = 0; i < MIN(io->domain->pwdHistoryLength-1, io->o.nt_history_len); i++) {
+       for (i = 0; i < MIN(io->ac->status->domain_data.pwdHistoryLength-1,
+                           io->o.nt_history_len); i++) {
                io->g.nt_history[i+1] = io->o.nt_history[i];
        }
        io->g.nt_history_len = i + 1;
@@ -183,26 +200,32 @@ static int setup_nt_fields(struct setup_password_fields_io *io)
        return LDB_SUCCESS;
 }
 
+/* Get the LANMAN hash, and fill it in as an entry in the password history, 
+   and specify it into io->g.lm_hash */
+
 static int setup_lm_fields(struct setup_password_fields_io *io)
 {
+       struct ldb_context *ldb;
        uint32_t i;
 
        io->g.lm_hash = io->n.lm_hash;
+       ldb = ldb_module_get_ctx(io->ac->module);
 
-       if (io->domain->pwdHistoryLength == 0) {
+       if (io->ac->status->domain_data.pwdHistoryLength == 0) {
                return LDB_SUCCESS;
        }
 
        /* We might not have an old NT password */
        io->g.lm_history = talloc_array(io->ac,
                                        struct samr_Password,
-                                       io->domain->pwdHistoryLength);
+                                       io->ac->status->domain_data.pwdHistoryLength);
        if (!io->g.lm_history) {
-               ldb_oom(io->ac->module->ldb);
+               ldb_oom(ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       for (i = 0; i < MIN(io->domain->pwdHistoryLength-1, io->o.lm_history_len); i++) {
+       for (i = 0; i < MIN(io->ac->status->domain_data.pwdHistoryLength-1,
+                           io->o.lm_history_len); i++) {
                io->g.lm_history[i+1] = io->o.lm_history[i];
        }
        io->g.lm_history_len = i + 1;
@@ -216,21 +239,18 @@ static int setup_lm_fields(struct setup_password_fields_io *io)
        return LDB_SUCCESS;
 }
 
-static int setup_primary_kerberos(struct setup_password_fields_io *io,
-                                 const struct supplementalCredentialsBlob *old_scb,
-                                 struct package_PrimaryKerberosBlob *pkb)
+static int setup_kerberos_keys(struct setup_password_fields_io *io)
 {
+       struct ldb_context *ldb;
        krb5_error_code krb5_ret;
        Principal *salt_principal;
        krb5_salt salt;
        krb5_keyblock key;
-       uint32_t k=0;
-       struct package_PrimaryKerberosCtr3 *pkb3 = &pkb->ctr.ctr3;
-       struct supplementalCredentialsPackage *old_scp = NULL;
-       struct package_PrimaryKerberosBlob _old_pkb;
-       struct package_PrimaryKerberosCtr3 *old_pkb3 = NULL;
-       uint32_t i;
-       enum ndr_err_code ndr_err;
+       krb5_data cleartext_data;
+
+       ldb = ldb_module_get_ctx(io->ac->module);
+       cleartext_data.data = io->n.cleartext_utf8->data;
+       cleartext_data.length = io->n.cleartext_utf8->length;
 
        /* Many, many thanks to lukeh@padl.com for this
         * algorithm, described in his Nov 10 2004 mail to
@@ -243,9 +263,9 @@ static int setup_primary_kerberos(struct setup_password_fields_io *io,
                char *name;
                char *saltbody;
 
-               name = talloc_strdup(io->ac, io->u.sAMAccountName);
+               name = strlower_talloc(io->ac, io->u.sAMAccountName);
                if (!name) {
-                       ldb_oom(io->ac->module->ldb);
+                       ldb_oom(ldb);
                        return LDB_ERR_OPERATIONS_ERROR;
                }
 
@@ -253,23 +273,24 @@ static int setup_primary_kerberos(struct setup_password_fields_io *io,
                        name[strlen(name)-1] = '\0';
                }
 
-               saltbody = talloc_asprintf(io->ac, "%s.%s", name, io->domain->dns_domain);
+               saltbody = talloc_asprintf(io->ac, "%s.%s", name,
+                                          io->ac->status->domain_data.dns_domain);
                if (!saltbody) {
-                       ldb_oom(io->ac->module->ldb);
+                       ldb_oom(ldb);
                        return LDB_ERR_OPERATIONS_ERROR;
                }
                
                krb5_ret = krb5_make_principal(io->smb_krb5_context->krb5_context,
                                               &salt_principal,
-                                              io->domain->realm, "host",
-                                              saltbody, NULL);
+                                              io->ac->status->domain_data.realm,
+                                              "host", saltbody, NULL);
        } else if (io->u.user_principal_name) {
                char *user_principal_name;
                char *p;
 
                user_principal_name = talloc_strdup(io->ac, io->u.user_principal_name);
                if (!user_principal_name) {
-                       ldb_oom(io->ac->module->ldb);
+                       ldb_oom(ldb);
                        return LDB_ERR_OPERATIONS_ERROR;
                }
 
@@ -280,19 +301,20 @@ static int setup_primary_kerberos(struct setup_password_fields_io *io,
 
                krb5_ret = krb5_make_principal(io->smb_krb5_context->krb5_context,
                                               &salt_principal,
-                                              io->domain->realm, user_principal_name,
-                                              NULL);
+                                              io->ac->status->domain_data.realm,
+                                              user_principal_name, NULL);
        } else {
                krb5_ret = krb5_make_principal(io->smb_krb5_context->krb5_context,
                                               &salt_principal,
-                                              io->domain->realm, io->u.sAMAccountName,
-                                              NULL);
+                                              io->ac->status->domain_data.realm,
+                                              io->u.sAMAccountName, NULL);
        }
        if (krb5_ret) {
-               ldb_asprintf_errstring(io->ac->module->ldb,
-                                      "setup_primary_kerberos: "
+               ldb_asprintf_errstring(ldb,
+                                      "setup_kerberos_keys: "
                                       "generation of a salting principal failed: %s",
-                                      smb_get_krb5_error_message(io->smb_krb5_context->krb5_context, krb5_ret, io->ac));
+                                      smb_get_krb5_error_message(io->smb_krb5_context->krb5_context,
+                                                                 krb5_ret, io->ac));
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
@@ -303,142 +325,171 @@ static int setup_primary_kerberos(struct setup_password_fields_io *io,
                                    salt_principal, &salt);
        krb5_free_principal(io->smb_krb5_context->krb5_context, salt_principal);
        if (krb5_ret) {
-               ldb_asprintf_errstring(io->ac->module->ldb,
-                                      "setup_primary_kerberos: "
+               ldb_asprintf_errstring(ldb,
+                                      "setup_kerberos_keys: "
                                       "generation of krb5_salt failed: %s",
-                                      smb_get_krb5_error_message(io->smb_krb5_context->krb5_context, krb5_ret, io->ac));
+                                      smb_get_krb5_error_message(io->smb_krb5_context->krb5_context,
+                                                                 krb5_ret, io->ac));
                return LDB_ERR_OPERATIONS_ERROR;
        }
        /* create a talloc copy */
-       pkb3->salt.string = talloc_strndup(io->ac,
-                                         salt.saltvalue.data,
-                                         salt.saltvalue.length);
+       io->g.salt = talloc_strndup(io->ac,
+                                   (char *)salt.saltvalue.data,
+                                   salt.saltvalue.length);
        krb5_free_salt(io->smb_krb5_context->krb5_context, salt);
-       if (!pkb3->salt.string) {
-               ldb_oom(io->ac->module->ldb);
+       if (!io->g.salt) {
+               ldb_oom(ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       salt.saltvalue.data     = discard_const(pkb3->salt.string);
-       salt.saltvalue.length   = strlen(pkb3->salt.string);
+       salt.saltvalue.data     = discard_const(io->g.salt);
+       salt.saltvalue.length   = strlen(io->g.salt);
 
        /*
-        * prepare generation of keys
-        *
-        * ENCTYPE_AES256_CTS_HMAC_SHA1_96 (disabled by default)
-        * ENCTYPE_DES_CBC_MD5
-        * ENCTYPE_DES_CBC_CRC
-        *
-        * NOTE: update num_keys when you add another enctype!
+        * create ENCTYPE_AES256_CTS_HMAC_SHA1_96 key out of
+        * the salt and the cleartext password
         */
-       pkb3->num_keys  = 3;
-       pkb3->keys      = talloc_array(io->ac, struct package_PrimaryKerberosKey, pkb3->num_keys);
-       if (!pkb3->keys) {
-               ldb_oom(io->ac->module->ldb);
+       krb5_ret = krb5_string_to_key_data_salt(io->smb_krb5_context->krb5_context,
+                                               ENCTYPE_AES256_CTS_HMAC_SHA1_96,
+                                               cleartext_data,
+                                               salt,
+                                               &key);
+       if (krb5_ret) {
+               ldb_asprintf_errstring(ldb,
+                                      "setup_kerberos_keys: "
+                                      "generation of a aes256-cts-hmac-sha1-96 key failed: %s",
+                                      smb_get_krb5_error_message(io->smb_krb5_context->krb5_context,
+                                                                 krb5_ret, io->ac));
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       pkb3->unknown3  = talloc_zero_array(io->ac, uint64_t, pkb3->num_keys);
-       if (!pkb3->unknown3) {
-               ldb_oom(io->ac->module->ldb);
+       io->g.aes_256 = data_blob_talloc(io->ac,
+                                        key.keyvalue.data,
+                                        key.keyvalue.length);
+       krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
+       if (!io->g.aes_256.data) {
+               ldb_oom(ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       if (lp_parm_bool(ldb_get_opaque(io->ac->module->ldb, "loadparm"), NULL, "password_hash", "create_aes_key", false)) {
-       /*
-        * TODO:
-        *
-        * w2k and w2k3 doesn't support AES, so we'll not include
-        * the AES key here yet.
-        *
-        * Also we don't have an example supplementalCredentials blob
-        * from Windows Longhorn Server with AES support
-        *
-        */
        /*
-        * create ENCTYPE_AES256_CTS_HMAC_SHA1_96 key out of
+        * create ENCTYPE_AES128_CTS_HMAC_SHA1_96 key out of
         * the salt and the cleartext password
         */
-       krb5_ret = krb5_string_to_key_salt(io->smb_krb5_context->krb5_context,
-                                          ENCTYPE_AES256_CTS_HMAC_SHA1_96,
-                                          io->n.cleartext,
-                                          salt,
-                                          &key);
-       pkb3->keys[k].keytype   = ENCTYPE_AES256_CTS_HMAC_SHA1_96;
-       pkb3->keys[k].value     = talloc(pkb3->keys, DATA_BLOB);
-       if (!pkb3->keys[k].value) {
-               krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
-               ldb_oom(io->ac->module->ldb);
+       krb5_ret = krb5_string_to_key_data_salt(io->smb_krb5_context->krb5_context,
+                                               ENCTYPE_AES128_CTS_HMAC_SHA1_96,
+                                               cleartext_data,
+                                               salt,
+                                               &key);
+       if (krb5_ret) {
+               ldb_asprintf_errstring(ldb,
+                                      "setup_kerberos_keys: "
+                                      "generation of a aes128-cts-hmac-sha1-96 key failed: %s",
+                                      smb_get_krb5_error_message(io->smb_krb5_context->krb5_context,
+                                                                 krb5_ret, io->ac));
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       *pkb3->keys[k].value    = data_blob_talloc(pkb3->keys[k].value,
-                                                  key.keyvalue.data,
-                                                  key.keyvalue.length);
+       io->g.aes_128 = data_blob_talloc(io->ac,
+                                        key.keyvalue.data,
+                                        key.keyvalue.length);
        krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
-       if (!pkb3->keys[k].value->data) {
-               ldb_oom(io->ac->module->ldb);
+       if (!io->g.aes_128.data) {
+               ldb_oom(ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       k++;
-}
 
        /*
         * create ENCTYPE_DES_CBC_MD5 key out of
         * the salt and the cleartext password
         */
-       krb5_ret = krb5_string_to_key_salt(io->smb_krb5_context->krb5_context,
-                                          ENCTYPE_DES_CBC_MD5,
-                                          io->n.cleartext,
-                                          salt,
-                                          &key);
-       pkb3->keys[k].keytype   = ENCTYPE_DES_CBC_MD5;
-       pkb3->keys[k].value     = talloc(pkb3->keys, DATA_BLOB);
-       if (!pkb3->keys[k].value) {
-               krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
-               ldb_oom(io->ac->module->ldb);
+       krb5_ret = krb5_string_to_key_data_salt(io->smb_krb5_context->krb5_context,
+                                               ENCTYPE_DES_CBC_MD5,
+                                               cleartext_data,
+                                               salt,
+                                               &key);
+       if (krb5_ret) {
+               ldb_asprintf_errstring(ldb,
+                                      "setup_kerberos_keys: "
+                                      "generation of a des-cbc-md5 key failed: %s",
+                                      smb_get_krb5_error_message(io->smb_krb5_context->krb5_context,
+                                                                 krb5_ret, io->ac));
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       *pkb3->keys[k].value    = data_blob_talloc(pkb3->keys[k].value,
-                                                  key.keyvalue.data,
-                                                  key.keyvalue.length);
+       io->g.des_md5 = data_blob_talloc(io->ac,
+                                        key.keyvalue.data,
+                                        key.keyvalue.length);
        krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
-       if (!pkb3->keys[k].value->data) {
-               ldb_oom(io->ac->module->ldb);
+       if (!io->g.des_md5.data) {
+               ldb_oom(ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       k++;
 
        /*
         * create ENCTYPE_DES_CBC_CRC key out of
         * the salt and the cleartext password
         */
-       krb5_ret = krb5_string_to_key_salt(io->smb_krb5_context->krb5_context,
-                                          ENCTYPE_DES_CBC_CRC,
-                                          io->n.cleartext,
-                                          salt,
-                                          &key);
-       pkb3->keys[k].keytype   = ENCTYPE_DES_CBC_CRC;
-       pkb3->keys[k].value     = talloc(pkb3->keys, DATA_BLOB);
-       if (!pkb3->keys[k].value) {
-               krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
-               ldb_oom(io->ac->module->ldb);
+       krb5_ret = krb5_string_to_key_data_salt(io->smb_krb5_context->krb5_context,
+                                               ENCTYPE_DES_CBC_CRC,
+                                               cleartext_data,
+                                               salt,
+                                               &key);
+       if (krb5_ret) {
+               ldb_asprintf_errstring(ldb,
+                                      "setup_kerberos_keys: "
+                                      "generation of a des-cbc-crc key failed: %s",
+                                      smb_get_krb5_error_message(io->smb_krb5_context->krb5_context,
+                                                                 krb5_ret, io->ac));
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       *pkb3->keys[k].value    = data_blob_talloc(pkb3->keys[k].value,
-                                                  key.keyvalue.data,
-                                                  key.keyvalue.length);
+       io->g.des_crc = data_blob_talloc(io->ac,
+                                        key.keyvalue.data,
+                                        key.keyvalue.length);
        krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
-       if (!pkb3->keys[k].value->data) {
-               ldb_oom(io->ac->module->ldb);
+       if (!io->g.des_crc.data) {
+               ldb_oom(ldb);
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       return LDB_SUCCESS;
+}
+
+static int setup_primary_kerberos(struct setup_password_fields_io *io,
+                                 const struct supplementalCredentialsBlob *old_scb,
+                                 struct package_PrimaryKerberosBlob *pkb)
+{
+       struct ldb_context *ldb;
+       struct package_PrimaryKerberosCtr3 *pkb3 = &pkb->ctr.ctr3;
+       struct supplementalCredentialsPackage *old_scp = NULL;
+       struct package_PrimaryKerberosBlob _old_pkb;
+       struct package_PrimaryKerberosCtr3 *old_pkb3 = NULL;
+       uint32_t i;
+       enum ndr_err_code ndr_err;
+
+       ldb = ldb_module_get_ctx(io->ac->module);
+
+       /*
+        * prepare generation of keys
+        *
+        * ENCTYPE_DES_CBC_MD5
+        * ENCTYPE_DES_CBC_CRC
+        */
+       pkb->version            = 3;
+       pkb3->salt.string       = io->g.salt;
+       pkb3->num_keys          = 2;
+       pkb3->keys              = talloc_array(io->ac,
+                                              struct package_PrimaryKerberosKey3,
+                                              pkb3->num_keys);
+       if (!pkb3->keys) {
+               ldb_oom(ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       k++;
 
-       /* fix up key number */
-       pkb3->num_keys = k;
+       pkb3->keys[0].keytype   = ENCTYPE_DES_CBC_MD5;
+       pkb3->keys[0].value     = &io->g.des_md5;
+       pkb3->keys[1].keytype   = ENCTYPE_DES_CBC_CRC;
+       pkb3->keys[1].value     = &io->g.des_crc;
 
        /* initialize the old keys to zero */
        pkb3->num_old_keys      = 0;
        pkb3->old_keys          = NULL;
-       pkb3->unknown3_old      = NULL;
 
        /* if there're no old keys, then we're done */
        if (!old_scb) {
@@ -446,10 +497,6 @@ static int setup_primary_kerberos(struct setup_password_fields_io *io,
        }
 
        for (i=0; i < old_scb->sub.num_packages; i++) {
-               if (old_scb->sub.packages[i].unknown1 != 0x00000001) {
-                       continue;
-               }
-
                if (strcmp("Primary:Kerberos", old_scb->sub.packages[i].name) != 0) {
                        continue;
                }
@@ -465,19 +512,18 @@ static int setup_primary_kerberos(struct setup_password_fields_io *io,
        if (old_scp) {
                DATA_BLOB blob;
 
-               blob = strhex_to_data_blob(old_scp->data);
+               blob = strhex_to_data_blob(io->ac, old_scp->data);
                if (!blob.data) {
-                       ldb_oom(io->ac->module->ldb);
+                       ldb_oom(ldb);
                        return LDB_ERR_OPERATIONS_ERROR;
                }
-               talloc_steal(io->ac, blob.data);
 
                /* TODO: use ndr_pull_struct_blob_all(), when the ndr layer handles it correct with relative pointers */
-               ndr_err = ndr_pull_struct_blob(&blob, io->ac, lp_iconv_convenience(ldb_get_opaque(io->ac->module->ldb, "loadparm")), &_old_pkb,
+               ndr_err = ndr_pull_struct_blob(&blob, io->ac, lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")), &_old_pkb,
                                               (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
                if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
                        NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
-                       ldb_asprintf_errstring(io->ac->module->ldb,
+                       ldb_asprintf_errstring(ldb,
                                               "setup_primary_kerberos: "
                                               "failed to pull old package_PrimaryKerberosBlob: %s",
                                               nt_errstr(status));
@@ -485,7 +531,7 @@ static int setup_primary_kerberos(struct setup_password_fields_io *io,
                }
 
                if (_old_pkb.version != 3) {
-                       ldb_asprintf_errstring(io->ac->module->ldb,
+                       ldb_asprintf_errstring(ldb,
                                               "setup_primary_kerberos: "
                                               "package_PrimaryKerberosBlob version[%u] expected[3]",
                                               _old_pkb.version);
@@ -503,7 +549,126 @@ static int setup_primary_kerberos(struct setup_password_fields_io *io,
        /* fill in the old keys */
        pkb3->num_old_keys      = old_pkb3->num_keys;
        pkb3->old_keys          = old_pkb3->keys;
-       pkb3->unknown3_old      = old_pkb3->unknown3;
+
+       return LDB_SUCCESS;
+}
+
+static int setup_primary_kerberos_newer(struct setup_password_fields_io *io,
+                                       const struct supplementalCredentialsBlob *old_scb,
+                                       struct package_PrimaryKerberosBlob *pkb)
+{
+       struct ldb_context *ldb;
+       struct package_PrimaryKerberosCtr4 *pkb4 = &pkb->ctr.ctr4;
+       struct supplementalCredentialsPackage *old_scp = NULL;
+       struct package_PrimaryKerberosBlob _old_pkb;
+       struct package_PrimaryKerberosCtr4 *old_pkb4 = NULL;
+       uint32_t i;
+       enum ndr_err_code ndr_err;
+
+       ldb = ldb_module_get_ctx(io->ac->module);
+
+       /*
+        * prepare generation of keys
+        *
+        * ENCTYPE_AES256_CTS_HMAC_SHA1_96
+        * ENCTYPE_AES128_CTS_HMAC_SHA1_96
+        * ENCTYPE_DES_CBC_MD5
+        * ENCTYPE_DES_CBC_CRC
+        */
+       pkb->version                    = 4;
+       pkb4->salt.string               = io->g.salt;
+       pkb4->default_iteration_count   = 4096;
+       pkb4->num_keys                  = 4;
+
+       pkb4->keys = talloc_array(io->ac,
+                                 struct package_PrimaryKerberosKey4,
+                                 pkb4->num_keys);
+       if (!pkb4->keys) {
+               ldb_oom(ldb);
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       pkb4->keys[0].iteration_count   = 4096;
+       pkb4->keys[0].keytype           = ENCTYPE_AES256_CTS_HMAC_SHA1_96;
+       pkb4->keys[0].value             = &io->g.aes_256;
+       pkb4->keys[1].iteration_count   = 4096;
+       pkb4->keys[1].keytype           = ENCTYPE_AES128_CTS_HMAC_SHA1_96;
+       pkb4->keys[1].value             = &io->g.aes_128;
+       pkb4->keys[2].iteration_count   = 4096;
+       pkb4->keys[2].keytype           = ENCTYPE_DES_CBC_MD5;
+       pkb4->keys[2].value             = &io->g.des_md5;
+       pkb4->keys[3].iteration_count   = 4096;
+       pkb4->keys[3].keytype           = ENCTYPE_DES_CBC_CRC;
+       pkb4->keys[3].value             = &io->g.des_crc;
+
+       /* initialize the old keys to zero */
+       pkb4->num_old_keys      = 0;
+       pkb4->old_keys          = NULL;
+       pkb4->num_older_keys    = 0;
+       pkb4->older_keys        = NULL;
+
+       /* if there're no old keys, then we're done */
+       if (!old_scb) {
+               return LDB_SUCCESS;
+       }
+
+       for (i=0; i < old_scb->sub.num_packages; i++) {
+               if (strcmp("Primary:Kerberos-Newer-Keys", old_scb->sub.packages[i].name) != 0) {
+                       continue;
+               }
+
+               if (!old_scb->sub.packages[i].data || !old_scb->sub.packages[i].data[0]) {
+                       continue;
+               }
+
+               old_scp = &old_scb->sub.packages[i];
+               break;
+       }
+       /* Primary:Kerberos-Newer-Keys element of supplementalCredentials */
+       if (old_scp) {
+               DATA_BLOB blob;
+
+               blob = strhex_to_data_blob(io->ac, old_scp->data);
+               if (!blob.data) {
+                       ldb_oom(ldb);
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+
+               /* TODO: use ndr_pull_struct_blob_all(), when the ndr layer handles it correct with relative pointers */
+               ndr_err = ndr_pull_struct_blob(&blob, io->ac,
+                                              lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")),
+                                              &_old_pkb,
+                                              (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
+               if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
+                       NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
+                       ldb_asprintf_errstring(ldb,
+                                              "setup_primary_kerberos_newer: "
+                                              "failed to pull old package_PrimaryKerberosBlob: %s",
+                                              nt_errstr(status));
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+
+               if (_old_pkb.version != 4) {
+                       ldb_asprintf_errstring(ldb,
+                                              "setup_primary_kerberos_newer: "
+                                              "package_PrimaryKerberosBlob version[%u] expected[4]",
+                                              _old_pkb.version);
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+
+               old_pkb4 = &_old_pkb.ctr.ctr4;
+       }
+
+       /* if we didn't found the old keys we're done */
+       if (!old_pkb4) {
+               return LDB_SUCCESS;
+       }
+
+       /* fill in the old keys */
+       pkb4->num_old_keys      = old_pkb4->num_keys;
+       pkb4->old_keys          = old_pkb4->keys;
+       pkb4->num_older_keys    = old_pkb4->num_old_keys;
+       pkb4->older_keys        = old_pkb4->old_keys;
 
        return LDB_SUCCESS;
 }
@@ -512,6 +677,7 @@ static int setup_primary_wdigest(struct setup_password_fields_io *io,
                                 const struct supplementalCredentialsBlob *old_scb,
                                 struct package_PrimaryWDigestBlob *pdb)
 {
+       struct ldb_context *ldb = ldb_module_get_ctx(io->ac->module);
        DATA_BLOB sAMAccountName;
        DATA_BLOB sAMAccountName_l;
        DATA_BLOB sAMAccountName_u;
@@ -525,7 +691,6 @@ static int setup_primary_wdigest(struct setup_password_fields_io *io,
        DATA_BLOB dns_domain;
        DATA_BLOB dns_domain_l;
        DATA_BLOB dns_domain_u;
-       DATA_BLOB cleartext;
        DATA_BLOB digest;
        DATA_BLOB delim;
        DATA_BLOB backslash;
@@ -759,12 +924,12 @@ static int setup_primary_wdigest(struct setup_password_fields_io *io,
        sAMAccountName          = data_blob_string_const(io->u.sAMAccountName);
        sAMAccountName_l        = data_blob_string_const(strlower_talloc(io->ac, io->u.sAMAccountName));
        if (!sAMAccountName_l.data) {
-               ldb_oom(io->ac->module->ldb);
+               ldb_oom(ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
        sAMAccountName_u        = data_blob_string_const(strupper_talloc(io->ac, io->u.sAMAccountName));
        if (!sAMAccountName_u.data) {
-               ldb_oom(io->ac->module->ldb);
+               ldb_oom(ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
@@ -772,41 +937,41 @@ static int setup_primary_wdigest(struct setup_password_fields_io *io,
        if (!user_principal_name) {
                user_principal_name = talloc_asprintf(io->ac, "%s@%s",
                                                      io->u.sAMAccountName,
-                                                     io->domain->dns_domain);
+                                                     io->ac->status->domain_data.dns_domain);
                if (!user_principal_name) {
-                       ldb_oom(io->ac->module->ldb);
+                       ldb_oom(ldb);
                        return LDB_ERR_OPERATIONS_ERROR;
                }       
        }
        userPrincipalName       = data_blob_string_const(user_principal_name);
        userPrincipalName_l     = data_blob_string_const(strlower_talloc(io->ac, user_principal_name));
        if (!userPrincipalName_l.data) {
-               ldb_oom(io->ac->module->ldb);
+               ldb_oom(ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
        userPrincipalName_u     = data_blob_string_const(strupper_talloc(io->ac, user_principal_name));
        if (!userPrincipalName_u.data) {
-               ldb_oom(io->ac->module->ldb);
+               ldb_oom(ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       netbios_domain          = data_blob_string_const(io->domain->netbios_domain);
-       netbios_domain_l        = data_blob_string_const(strlower_talloc(io->ac, io->domain->netbios_domain));
+       netbios_domain          = data_blob_string_const(io->ac->status->domain_data.netbios_domain);
+       netbios_domain_l        = data_blob_string_const(strlower_talloc(io->ac,
+                                                                        io->ac->status->domain_data.netbios_domain));
        if (!netbios_domain_l.data) {
-               ldb_oom(io->ac->module->ldb);
+               ldb_oom(ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       netbios_domain_u        = data_blob_string_const(strupper_talloc(io->ac, io->domain->netbios_domain));
+       netbios_domain_u        = data_blob_string_const(strupper_talloc(io->ac,
+                                                                        io->ac->status->domain_data.netbios_domain));
        if (!netbios_domain_u.data) {
-               ldb_oom(io->ac->module->ldb);
+               ldb_oom(ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       dns_domain              = data_blob_string_const(io->domain->dns_domain);
-       dns_domain_l            = data_blob_string_const(io->domain->dns_domain);
-       dns_domain_u            = data_blob_string_const(io->domain->realm);
-
-       cleartext               = data_blob_string_const(io->n.cleartext);
+       dns_domain              = data_blob_string_const(io->ac->status->domain_data.dns_domain);
+       dns_domain_l            = data_blob_string_const(io->ac->status->domain_data.dns_domain);
+       dns_domain_u            = data_blob_string_const(io->ac->status->domain_data.realm);
 
        digest                  = data_blob_string_const("Digest");
 
@@ -814,9 +979,10 @@ static int setup_primary_wdigest(struct setup_password_fields_io *io,
        backslash               = data_blob_string_const("\\");
 
        pdb->num_hashes = ARRAY_SIZE(wdigest);
-       pdb->hashes     = talloc_array(io->ac, struct package_PrimaryWDigestHash, pdb->num_hashes);
+       pdb->hashes     = talloc_array(io->ac, struct package_PrimaryWDigestHash,
+                                      pdb->num_hashes);
        if (!pdb->hashes) {
-               ldb_oom(io->ac->module->ldb);
+               ldb_oom(ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
@@ -833,7 +999,7 @@ static int setup_primary_wdigest(struct setup_password_fields_io *io,
                        MD5Update(&md5, wdigest[i].realm->data, wdigest[i].realm->length);
                }
                MD5Update(&md5, delim.data, delim.length);
-               MD5Update(&md5, cleartext.data, cleartext.length);
+               MD5Update(&md5, io->n.cleartext_utf8->data, io->n.cleartext_utf8->length);
                MD5Final(pdb->hashes[i].hash, &md5);
        }
 
@@ -842,35 +1008,56 @@ static int setup_primary_wdigest(struct setup_password_fields_io *io,
 
 static int setup_supplemental_field(struct setup_password_fields_io *io)
 {
+       struct ldb_context *ldb;
        struct supplementalCredentialsBlob scb;
        struct supplementalCredentialsBlob _old_scb;
        struct supplementalCredentialsBlob *old_scb = NULL;
-       /* Packages + (Kerberos, WDigest and maybe CLEARTEXT) */
-       uint32_t num_packages = 1 + 2;
-       struct supplementalCredentialsPackage packages[1+3];
-       struct supplementalCredentialsPackage *pp = &packages[0];
-       struct supplementalCredentialsPackage *pk = &packages[1];
-       struct supplementalCredentialsPackage *pd = &packages[2];
-       struct supplementalCredentialsPackage *pc = NULL;
+       /* Packages + (Kerberos-Newer-Keys, Kerberos, WDigest and CLEARTEXT) */
+       uint32_t num_names = 0;
+       const char *names[1+4];
+       uint32_t num_packages = 0;
+       struct supplementalCredentialsPackage packages[1+4];
+       /* Packages */
+       struct supplementalCredentialsPackage *pp = NULL;
        struct package_PackagesBlob pb;
        DATA_BLOB pb_blob;
        char *pb_hexstr;
+       /* Primary:Kerberos-Newer-Keys */
+       const char **nkn = NULL;
+       struct supplementalCredentialsPackage *pkn = NULL;
+       struct package_PrimaryKerberosBlob pknb;
+       DATA_BLOB pknb_blob;
+       char *pknb_hexstr;
+       /* Primary:Kerberos */
+       const char **nk = NULL;
+       struct supplementalCredentialsPackage *pk = NULL;
        struct package_PrimaryKerberosBlob pkb;
        DATA_BLOB pkb_blob;
        char *pkb_hexstr;
+       /* Primary:WDigest */
+       const char **nd = NULL;
+       struct supplementalCredentialsPackage *pd = NULL;
        struct package_PrimaryWDigestBlob pdb;
        DATA_BLOB pdb_blob;
        char *pdb_hexstr;
+       /* Primary:CLEARTEXT */
+       const char **nc = NULL;
+       struct supplementalCredentialsPackage *pc = NULL;
        struct package_PrimaryCLEARTEXTBlob pcb;
        DATA_BLOB pcb_blob;
        char *pcb_hexstr;
        int ret;
        enum ndr_err_code ndr_err;
        uint8_t zero16[16];
+       bool do_newer_keys = false;
+       bool do_cleartext = false;
 
        ZERO_STRUCT(zero16);
+       ZERO_STRUCT(names);
+
+       ldb = ldb_module_get_ctx(io->ac->module);
 
-       if (!io->n.cleartext) {
+       if (!io->n.cleartext_utf8) {
                /* 
                 * when we don't have a cleartext password
                 * we can't setup a supplementalCredential value
@@ -880,33 +1067,112 @@ static int setup_supplemental_field(struct setup_password_fields_io *io)
 
        /* if there's an old supplementaCredentials blob then parse it */
        if (io->o.supplemental) {
-               ndr_err = ndr_pull_struct_blob_all(io->o.supplemental, io->ac, lp_iconv_convenience(ldb_get_opaque(io->ac->module->ldb, "loadparm")), &_old_scb,
+               ndr_err = ndr_pull_struct_blob_all(io->o.supplemental, io->ac,
+                                                  lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")),
+                                                  &_old_scb,
                                                   (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
                if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
                        NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
-                       ldb_asprintf_errstring(io->ac->module->ldb,
+                       ldb_asprintf_errstring(ldb,
                                               "setup_supplemental_field: "
                                               "failed to pull old supplementalCredentialsBlob: %s",
                                               nt_errstr(status));
                        return LDB_ERR_OPERATIONS_ERROR;
                }
 
-               old_scb = &_old_scb;
+               if (_old_scb.sub.signature == SUPPLEMENTAL_CREDENTIALS_SIGNATURE) {
+                       old_scb = &_old_scb;
+               } else {
+                       ldb_debug(ldb, LDB_DEBUG_ERROR,
+                                              "setup_supplemental_field: "
+                                              "supplementalCredentialsBlob signature[0x%04X] expected[0x%04X]",
+                                              _old_scb.sub.signature, SUPPLEMENTAL_CREDENTIALS_SIGNATURE);
+               }
+       }
+       /* Per MS-SAMR 3.1.1.8.11.6 we create AES keys if our domain functionality level is 2008 or higher */
+       do_newer_keys = (dsdb_functional_level(ldb) >= DS_DOMAIN_FUNCTION_2008);
+
+       if (io->ac->status->domain_data.store_cleartext &&
+           (io->u.userAccountControl & UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED)) {
+               do_cleartext = true;
+       }
+
+       /*
+        * The ordering is this
+        *
+        * Primary:Kerberos-Newer-Keys (optional)
+        * Primary:Kerberos
+        * Primary:WDigest
+        * Primary:CLEARTEXT (optional)
+        *
+        * And the 'Packages' package is insert before the last
+        * other package.
+        */
+       if (do_newer_keys) {
+               /* Primary:Kerberos-Newer-Keys */
+               nkn = &names[num_names++];
+               pkn = &packages[num_packages++];
+       }
+
+       /* Primary:Kerberos */
+       nk = &names[num_names++];
+       pk = &packages[num_packages++];
+
+       if (!do_cleartext) {
+               /* Packages */
+               pp = &packages[num_packages++];
        }
 
-       if (io->domain->store_cleartext &&
-           (io->u.user_account_control & UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED)) {
-               pc = &packages[3];
-               num_packages++;
+       /* Primary:WDigest */
+       nd = &names[num_names++];
+       pd = &packages[num_packages++];
+
+       if (do_cleartext) {
+               /* Packages */
+               pp = &packages[num_packages++];
+
+               /* Primary:CLEARTEXT */
+               nc = &names[num_names++];
+               pc = &packages[num_packages++];
        }
 
-       /* Kerberos, WDigest, CLEARTEXT and termination(counted by the Packages element) */
-       pb.names = talloc_zero_array(io->ac, const char *, num_packages);
+       if (pkn) {
+               /*
+                * setup 'Primary:Kerberos-Newer-Keys' element
+                */
+               *nkn = "Kerberos-Newer-Keys";
+
+               ret = setup_primary_kerberos_newer(io, old_scb, &pknb);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
+               }
+
+               ndr_err = ndr_push_struct_blob(&pknb_blob, io->ac,
+                                              lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")),
+                                              &pknb,
+                                              (ndr_push_flags_fn_t)ndr_push_package_PrimaryKerberosBlob);
+               if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
+                       NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
+                       ldb_asprintf_errstring(ldb,
+                                              "setup_supplemental_field: "
+                                              "failed to push package_PrimaryKerberosNeverBlob: %s",
+                                              nt_errstr(status));
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+               pknb_hexstr = data_blob_hex_string_upper(io->ac, &pknb_blob);
+               if (!pknb_hexstr) {
+                       ldb_oom(ldb);
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+               pkn->name       = "Primary:Kerberos-Newer-Keys";
+               pkn->reserved   = 1;
+               pkn->data       = pknb_hexstr;
+       }
 
        /*
         * setup 'Primary:Kerberos' element
         */
-       pb.names[0] = "Kerberos";
+       *nk = "Kerberos";
 
        ret = setup_primary_kerberos(io, old_scb, &pkb);
        if (ret != LDB_SUCCESS) {
@@ -914,30 +1180,30 @@ static int setup_supplemental_field(struct setup_password_fields_io *io)
        }
 
        ndr_err = ndr_push_struct_blob(&pkb_blob, io->ac, 
-                                      lp_iconv_convenience(ldb_get_opaque(io->ac->module->ldb, "loadparm")),
+                                      lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")),
                                       &pkb,
                                       (ndr_push_flags_fn_t)ndr_push_package_PrimaryKerberosBlob);
        if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
                NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
-               ldb_asprintf_errstring(io->ac->module->ldb,
+               ldb_asprintf_errstring(ldb,
                                       "setup_supplemental_field: "
                                       "failed to push package_PrimaryKerberosBlob: %s",
                                       nt_errstr(status));
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       pkb_hexstr = data_blob_hex_string(io->ac, &pkb_blob);
+       pkb_hexstr = data_blob_hex_string_upper(io->ac, &pkb_blob);
        if (!pkb_hexstr) {
-               ldb_oom(io->ac->module->ldb);
+               ldb_oom(ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
        pk->name        = "Primary:Kerberos";
-       pk->unknown1    = 1;
+       pk->reserved    = 1;
        pk->data        = pkb_hexstr;
 
        /*
         * setup 'Primary:WDigest' element
         */
-       pb.names[1] = "WDigest";
+       *nd = "WDigest";
 
        ret = setup_primary_wdigest(io, old_scb, &pdb);
        if (ret != LDB_SUCCESS) {
@@ -945,93 +1211,95 @@ static int setup_supplemental_field(struct setup_password_fields_io *io)
        }
 
        ndr_err = ndr_push_struct_blob(&pdb_blob, io->ac, 
-                                      lp_iconv_convenience(ldb_get_opaque(io->ac->module->ldb, "loadparm")),
+                                      lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")),
                                       &pdb,
                                       (ndr_push_flags_fn_t)ndr_push_package_PrimaryWDigestBlob);
        if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
                NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
-               ldb_asprintf_errstring(io->ac->module->ldb,
+               ldb_asprintf_errstring(ldb,
                                       "setup_supplemental_field: "
                                       "failed to push package_PrimaryWDigestBlob: %s",
                                       nt_errstr(status));
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       pdb_hexstr = data_blob_hex_string(io->ac, &pdb_blob);
+       pdb_hexstr = data_blob_hex_string_upper(io->ac, &pdb_blob);
        if (!pdb_hexstr) {
-               ldb_oom(io->ac->module->ldb);
+               ldb_oom(ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
        pd->name        = "Primary:WDigest";
-       pd->unknown1    = 1;
+       pd->reserved    = 1;
        pd->data        = pdb_hexstr;
 
        /*
         * setup 'Primary:CLEARTEXT' element
         */
        if (pc) {
-               pb.names[2]     = "CLEARTEXT";
+               *nc             = "CLEARTEXT";
 
-               pcb.cleartext   = io->n.cleartext;
+               pcb.cleartext   = *io->n.cleartext_utf16;
 
                ndr_err = ndr_push_struct_blob(&pcb_blob, io->ac, 
-                                              lp_iconv_convenience(ldb_get_opaque(io->ac->module->ldb, "loadparm")),
+                                              lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")),
                                               &pcb,
                                               (ndr_push_flags_fn_t)ndr_push_package_PrimaryCLEARTEXTBlob);
                if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
                        NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
-                       ldb_asprintf_errstring(io->ac->module->ldb,
+                       ldb_asprintf_errstring(ldb,
                                               "setup_supplemental_field: "
                                               "failed to push package_PrimaryCLEARTEXTBlob: %s",
                                               nt_errstr(status));
                        return LDB_ERR_OPERATIONS_ERROR;
                }
-               pcb_hexstr = data_blob_hex_string(io->ac, &pcb_blob);
+               pcb_hexstr = data_blob_hex_string_upper(io->ac, &pcb_blob);
                if (!pcb_hexstr) {
-                       ldb_oom(io->ac->module->ldb);
+                       ldb_oom(ldb);
                        return LDB_ERR_OPERATIONS_ERROR;
                }
                pc->name        = "Primary:CLEARTEXT";
-               pc->unknown1    = 1;
+               pc->reserved    = 1;
                pc->data        = pcb_hexstr;
        }
 
        /*
         * setup 'Packages' element
         */
+       pb.names = names;
        ndr_err = ndr_push_struct_blob(&pb_blob, io->ac, 
-                                      lp_iconv_convenience(ldb_get_opaque(io->ac->module->ldb, "loadparm")), 
+                                      lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")), 
                                       &pb,
                                       (ndr_push_flags_fn_t)ndr_push_package_PackagesBlob);
        if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
                NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
-               ldb_asprintf_errstring(io->ac->module->ldb,
+               ldb_asprintf_errstring(ldb,
                                       "setup_supplemental_field: "
                                       "failed to push package_PackagesBlob: %s",
                                       nt_errstr(status));
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       pb_hexstr = data_blob_hex_string(io->ac, &pb_blob);
+       pb_hexstr = data_blob_hex_string_upper(io->ac, &pb_blob);
        if (!pb_hexstr) {
-               ldb_oom(io->ac->module->ldb);
+               ldb_oom(ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
        pp->name        = "Packages";
-       pp->unknown1    = 2;
+       pp->reserved    = 2;
        pp->data        = pb_hexstr;
 
        /*
         * setup 'supplementalCredentials' value
         */
+       ZERO_STRUCT(scb);
        scb.sub.num_packages    = num_packages;
        scb.sub.packages        = packages;
 
        ndr_err = ndr_push_struct_blob(&io->g.supplemental, io->ac, 
-                                      lp_iconv_convenience(ldb_get_opaque(io->ac->module->ldb, "loadparm")),
+                                      lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")),
                                       &scb,
                                       (ndr_push_flags_fn_t)ndr_push_supplementalCredentialsBlob);
        if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
                NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
-               ldb_asprintf_errstring(io->ac->module->ldb,
+               ldb_asprintf_errstring(ldb,
                                       "setup_supplemental_field: "
                                       "failed to push supplementalCredentialsBlob: %s",
                                       nt_errstr(status));
@@ -1049,278 +1317,893 @@ static int setup_last_set_field(struct setup_password_fields_io *io)
        return LDB_SUCCESS;
 }
 
-static int setup_kvno_field(struct setup_password_fields_io *io)
+static int setup_given_passwords(struct setup_password_fields_io *io,
+                                struct setup_password_fields_given *g)
 {
-       /* increment by one */
-       io->g.kvno = io->o.kvno + 1;
+       struct ldb_context *ldb;
+       bool ok;
 
-       return LDB_SUCCESS;
-}
+       ldb = ldb_module_get_ctx(io->ac->module);
 
-static int setup_password_fields(struct setup_password_fields_io *io)
-{
-       bool ok;
-       int ret;
+       if (g->cleartext_utf8) {
+               char **cleartext_utf16_str;
+               struct ldb_val *cleartext_utf16_blob;
+               size_t converted_pw_len;
 
-       /*
-        * refuse the change if someone want to change the cleartext
-        * and supply his own hashes at the same time...
-        */
-       if (io->n.cleartext && (io->n.nt_hash || io->n.lm_hash)) {
-               ldb_asprintf_errstring(io->ac->module->ldb,
-                                      "setup_password_fields: "
-                                      "it's only allowed to set the cleartext password or the password hashes");
-               return LDB_ERR_UNWILLING_TO_PERFORM;
+               cleartext_utf16_blob = talloc(io->ac, struct ldb_val);
+               if (!cleartext_utf16_blob) {
+                       ldb_oom(ldb);
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+               if (!convert_string_talloc_convenience(io->ac,
+                                                      lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")),
+                                                      CH_UTF8, CH_UTF16,
+                                                      g->cleartext_utf8->data,
+                                                      g->cleartext_utf8->length,
+                                                      (void *)&cleartext_utf16_str,
+                                                      &converted_pw_len, false)) {
+                       ldb_asprintf_errstring(ldb,
+                               "setup_password_fields: "
+                               "failed to generate UTF16 password from cleartext UTF8 password");
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+               *cleartext_utf16_blob = data_blob_const(cleartext_utf16_str,
+                                                       converted_pw_len);
+               g->cleartext_utf16 = cleartext_utf16_blob;
+       } else if (g->cleartext_utf16) {
+               char *cleartext_utf8_str;
+               struct ldb_val *cleartext_utf8_blob;
+               size_t converted_pw_len;
+
+               cleartext_utf8_blob = talloc(io->ac, struct ldb_val);
+               if (!cleartext_utf8_blob) {
+                       ldb_oom(ldb);
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+               if (!convert_string_talloc_convenience(io->ac,
+                                                      lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")),
+                                                      CH_UTF16MUNGED, CH_UTF8,
+                                                      g->cleartext_utf16->data,
+                                                      g->cleartext_utf16->length,
+                                                      (void *)&cleartext_utf8_str,
+                                                      &converted_pw_len, false)) {
+                       /* We can't bail out entirely, as these unconvertable passwords are frustratingly valid */
+                       talloc_free(cleartext_utf8_blob);
+               } else {
+                       *cleartext_utf8_blob = data_blob_const(cleartext_utf8_str,
+                                                              converted_pw_len);
+                       g->cleartext_utf8 = cleartext_utf8_blob;
+               }
        }
 
-       if (io->n.cleartext && !io->n.nt_hash) {
-               struct samr_Password *hash;
+       if (g->cleartext_utf16) {
+               struct samr_Password *nt_hash;
 
-               hash = talloc(io->ac, struct samr_Password);
-               if (!hash) {
-                       ldb_oom(io->ac->module->ldb);
+               nt_hash = talloc(io->ac, struct samr_Password);
+               if (!nt_hash) {
+                       ldb_oom(ldb);
                        return LDB_ERR_OPERATIONS_ERROR;
                }
+               g->nt_hash = nt_hash;
 
                /* compute the new nt hash */
-               ok = E_md4hash(io->n.cleartext, hash->hash);
-               if (ok) {
-                       io->n.nt_hash = hash;
-               } else {
-                       ldb_asprintf_errstring(io->ac->module->ldb,
-                                              "setup_password_fields: "
-                                              "failed to generate nthash from cleartext password");
-                       return LDB_ERR_OPERATIONS_ERROR;
-               }
+               mdfour(nt_hash->hash,
+                      g->cleartext_utf16->data,
+                      g->cleartext_utf16->length);
        }
 
-       if (io->n.cleartext && !io->n.lm_hash) {
-               struct samr_Password *hash;
+       if (g->cleartext_utf8 &&
+           lp_lanman_auth(ldb_get_opaque(ldb, "loadparm"))) {
+               struct samr_Password *lm_hash;
 
-               hash = talloc(io->ac, struct samr_Password);
-               if (!hash) {
-                       ldb_oom(io->ac->module->ldb);
+               lm_hash = talloc(io->ac, struct samr_Password);
+               if (!lm_hash) {
+                       ldb_oom(ldb);
                        return LDB_ERR_OPERATIONS_ERROR;
                }
 
                /* compute the new lm hash */
-               ok = E_deshash(io->n.cleartext, hash->hash);
+               ok = E_deshash((char *)g->cleartext_utf8->data, lm_hash->hash);
                if (ok) {
-                       io->n.lm_hash = hash;
+                       g->lm_hash = lm_hash;
                } else {
-                       talloc_free(hash->hash);
+                       talloc_free(lm_hash);
+               }
+       }
+
+       return LDB_SUCCESS;
+}
+
+static int setup_password_fields(struct setup_password_fields_io *io)
+{
+       struct ldb_context *ldb;
+       int ret;
+
+       ldb = ldb_module_get_ctx(io->ac->module);
+
+       /* transform the old password (for password changes) */
+       ret = setup_given_passwords(io, &io->og);
+       if (ret != LDB_SUCCESS) {
+               return ret;
+       }
+
+       /* transform the new password */
+       ret = setup_given_passwords(io, &io->n);
+       if (ret != LDB_SUCCESS) {
+               return ret;
+       }
+
+       if (io->n.cleartext_utf8) {
+               ret = setup_kerberos_keys(io);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
                }
        }
 
        ret = setup_nt_fields(io);
-       if (ret != 0) {
+       if (ret != LDB_SUCCESS) {
                return ret;
        }
 
        ret = setup_lm_fields(io);
-       if (ret != 0) {
+       if (ret != LDB_SUCCESS) {
                return ret;
        }
 
        ret = setup_supplemental_field(io);
-       if (ret != 0) {
+       if (ret != LDB_SUCCESS) {
                return ret;
        }
 
        ret = setup_last_set_field(io);
-       if (ret != 0) {
-               return ret;
-       }
-
-       ret = setup_kvno_field(io);
-       if (ret != 0) {
+       if (ret != LDB_SUCCESS) {
                return ret;
        }
 
        return LDB_SUCCESS;
 }
 
-static struct ldb_handle *ph_init_handle(struct ldb_request *req, struct ldb_module *module, enum ph_type type)
+static int check_password_restrictions(struct setup_password_fields_io *io)
 {
-       struct ph_context *ac;
-       struct ldb_handle *h;
+       struct ldb_context *ldb;
+       int ret;
+       enum samr_ValidationStatus stat;
+
+       ldb = ldb_module_get_ctx(io->ac->module);
+
+       /* First check the old password is correct, for password changes */
+       if (!io->ac->pwd_reset && !io->ac->change_old_pw_checked) {
+               /* we need to old nt or lm hash given by the client */
+               if (!io->og.nt_hash && !io->og.lm_hash) {
+                       ldb_asprintf_errstring(ldb,
+                               "check_password_restrictions: "
+                               "You need to provide the old password "
+                               "in order to change your password!");
+                       return LDB_ERR_UNWILLING_TO_PERFORM;
+               }
 
-       h = talloc_zero(req, struct ldb_handle);
-       if (h == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
-               return NULL;
+               if (io->og.nt_hash) {
+                       if (!io->o.nt_hash) {
+                               ldb_asprintf_errstring(ldb,
+                                       "check_password_restrictions: "
+                                       "There's no old nt_hash, which is needed "
+                                       "in order to change your password!");
+                               return LDB_ERR_UNWILLING_TO_PERFORM;
+                       }
+
+                       /* The password modify through the NT hash is encouraged
+                          and has no problems at all */
+                       if (memcmp(io->og.nt_hash->hash, io->o.nt_hash->hash, 16) != 0) {
+                               ldb_asprintf_errstring(ldb,
+                                       "check_password_restrictions: "
+                                       "The old password specified doesn't match!");
+                               return LDB_ERR_UNWILLING_TO_PERFORM;
+                       }
+               } else if (io->og.lm_hash) {
+                       struct loadparm_context *lp_ctx =
+                               (struct loadparm_context *)ldb_get_opaque(ldb, "loadparm");
+
+                       if (!lp_lanman_auth(lp_ctx)) {
+                               ldb_asprintf_errstring(ldb,
+                                       "check_password_restrictions: "
+                                       "The password change through the LM hash is deactivated!");
+                               return LDB_ERR_UNWILLING_TO_PERFORM;
+                       }
+
+                       if (!io->o.lm_hash) {
+                               ldb_asprintf_errstring(ldb,
+                                       "check_password_restrictions: "
+                                       "There's no old lm_hash, which is needed "
+                                       "in order to change your password!");
+                               return LDB_ERR_UNWILLING_TO_PERFORM;
+                       }
+
+                       if (memcmp(io->og.lm_hash->hash, io->o.lm_hash->hash, 16) != 0) {
+                               ldb_asprintf_errstring(ldb,
+                                       "check_password_restrictions: "
+                                       "The old password specified doesn't match!");
+                               return LDB_ERR_UNWILLING_TO_PERFORM;
+                       }
+               }
        }
 
-       h->module = module;
+       if (io->u.restrictions == 0) {
+               /* FIXME: Is this right? */
+               return LDB_SUCCESS;
+       }
 
-       ac = talloc_zero(h, struct ph_context);
-       if (ac == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
-               talloc_free(h);
-               return NULL;
+       /*
+        * Fundamental password checks done by the call
+        * "samdb_check_password".
+        * It is also in use by "dcesrv_samr_ValidatePassword".
+        */
+       if (io->n.cleartext_utf8 != NULL) {
+               stat = samdb_check_password(io->n.cleartext_utf8,
+                                           io->ac->status->domain_data.pwdProperties,
+                                           io->ac->status->domain_data.minPwdLength);
+               switch (stat) {
+               case SAMR_VALIDATION_STATUS_SUCCESS:
+                               /* perfect -> proceed! */
+                       break;
+
+               case SAMR_VALIDATION_STATUS_PWD_TOO_SHORT:
+                       ldb_asprintf_errstring(ldb,
+                               "check_password_restrictions: "
+                               "the password is too short. It should be equal or longer than %i characters!",
+                               io->ac->status->domain_data.minPwdLength);
+
+                       io->ac->status->reject_reason = SAM_PWD_CHANGE_PASSWORD_TOO_SHORT;
+                       return LDB_ERR_CONSTRAINT_VIOLATION;
+
+               case SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH:
+                       ldb_asprintf_errstring(ldb,
+                               "check_password_restrictions: "
+                               "the password does not meet the complexity criterias!");
+                       io->ac->status->reject_reason = SAM_PWD_CHANGE_NOT_COMPLEX;
+
+                       return LDB_ERR_CONSTRAINT_VIOLATION;
+
+               default:
+                       ldb_asprintf_errstring(ldb,
+                               "check_password_restrictions: "
+                               "the password doesn't fit by a certain reason!");
+
+                       return LDB_ERR_CONSTRAINT_VIOLATION;
+               }
+       }
+
+       if (io->ac->pwd_reset) {
+               return LDB_SUCCESS;
        }
 
-       h->private_data = (void *)ac;
+       if (io->n.nt_hash) {
+               uint32_t i;
 
-       h->state = LDB_ASYNC_INIT;
-       h->status = LDB_SUCCESS;
+               /* checks the NT hash password history */
+               for (i = 0; i < io->o.nt_history_len; i++) {
+                       ret = memcmp(io->n.nt_hash, io->o.nt_history[i].hash, 16);
+                       if (ret == 0) {
+                               ldb_asprintf_errstring(ldb,
+                                       "check_password_restrictions: "
+                                       "the password was already used (in history)!");
 
-       ac->type = type;
-       ac->module = module;
-       ac->orig_req = req;
+                               io->ac->status->reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
 
-       return h;
-}
+                               return LDB_ERR_CONSTRAINT_VIOLATION;
+                       }
+               }
+       }
 
-static int get_domain_data_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
-{
-       struct ph_context *ac;
+       if (io->n.lm_hash) {
+               uint32_t i;
 
-       ac = talloc_get_type(context, struct ph_context);
+               /* checks the LM hash password history */
+               for (i = 0; i < io->o.lm_history_len; i++) {
+                       ret = memcmp(io->n.nt_hash, io->o.lm_history[i].hash, 16);
+                       if (ret == 0) {
+                               ldb_asprintf_errstring(ldb,
+                                       "check_password_restrictions: "
+                                       "the password was already used (in history)!");
 
-       /* we are interested only in the single reply (base search) we receive here */
-       if (ares->type == LDB_REPLY_ENTRY) {
-               if (ac->dom_res != NULL) {
-                       ldb_set_errstring(ldb, "Too many results");
-                       talloc_free(ares);
-                       return LDB_ERR_OPERATIONS_ERROR;
+                               io->ac->status->reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
+
+                               return LDB_ERR_CONSTRAINT_VIOLATION;
+                       }
                }
-               ac->dom_res = talloc_steal(ac, ares);
-       } else {
-               talloc_free(ares);
        }
 
-       return LDB_SUCCESS;
-}
+       /* are all password changes disallowed? */
+       if (io->ac->status->domain_data.pwdProperties & DOMAIN_REFUSE_PASSWORD_CHANGE) {
+               ldb_asprintf_errstring(ldb,
+                       "check_password_restrictions: "
+                       "password changes disabled!");
+               return LDB_ERR_CONSTRAINT_VIOLATION;
+       }
 
-static int build_domain_data_request(struct ph_context *ac)
-{
-       /* attrs[] is returned from this function in
-          ac->dom_req->op.search.attrs, so it must be static, as
-          otherwise the compiler can put it on the stack */
-       static const char * const attrs[] = { "pwdProperties", "pwdHistoryLength", NULL };
-       char *filter;
+       /* can this user change the password? */
+       if (io->u.userAccountControl & UF_PASSWD_CANT_CHANGE) {
+               ldb_asprintf_errstring(ldb,
+                       "check_password_restrictions: "
+                       "password can't be changed on this account!");
+               return LDB_ERR_CONSTRAINT_VIOLATION;
+       }
 
-       ac->dom_req = talloc_zero(ac, struct ldb_request);
-       if (ac->dom_req == NULL) {
-               ldb_debug(ac->module->ldb, LDB_DEBUG_ERROR, "Out of Memory!\n");
-               return LDB_ERR_OPERATIONS_ERROR;
+       /* Password minimum age: yes, this is a minus. The ages are in negative 100nsec units! */
+       if (io->u.pwdLastSet - io->ac->status->domain_data.minPwdAge > io->g.last_set) {
+               ldb_asprintf_errstring(ldb,
+                       "check_password_restrictions: "
+                       "password is too young to change!");
+               return LDB_ERR_CONSTRAINT_VIOLATION;
        }
-       ac->dom_req->operation = LDB_SEARCH;
-       ac->dom_req->op.search.base = ldb_get_default_basedn(ac->module->ldb);
-       ac->dom_req->op.search.scope = LDB_SCOPE_SUBTREE;
 
-       filter = talloc_asprintf(ac->dom_req,
-                                "(&(objectSid=%s)(|(|(objectClass=domain)(objectClass=builtinDomain))(objectClass=samba4LocalDomain)))", 
-                                ldap_encode_ndr_dom_sid(ac->dom_req, ac->domain_sid));
-       if (filter == NULL) {
-               ldb_debug(ac->module->ldb, LDB_DEBUG_ERROR, "Out of Memory!\n");
-               talloc_free(ac->dom_req);
+       return LDB_SUCCESS;
+}
+
+static int setup_io(struct ph_context *ac, 
+                   const struct ldb_message *orig_msg,
+                   const struct ldb_message *searched_msg, 
+                   struct setup_password_fields_io *io) 
+{ 
+       const struct ldb_val *quoted_utf16, *old_quoted_utf16, *lm_hash, *old_lm_hash;
+       struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
+       int ret;
+
+       ZERO_STRUCTP(io);
+
+       /* Some operations below require kerberos contexts */
+
+       if (smb_krb5_init_context(ac,
+                                 ldb_get_event_context(ldb),
+                                 (struct loadparm_context *)ldb_get_opaque(ldb, "loadparm"),
+                                 &io->smb_krb5_context) != 0) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       ac->dom_req->op.search.tree = ldb_parse_tree(ac->dom_req, filter);
-       if (ac->dom_req->op.search.tree == NULL) {
-               ldb_set_errstring(ac->module->ldb, "Invalid search filter");
-               talloc_free(ac->dom_req);
+       io->ac                          = ac;
+
+       io->u.userAccountControl        = samdb_result_uint(searched_msg, "userAccountControl", 0);
+       io->u.pwdLastSet                = samdb_result_nttime(searched_msg, "pwdLastSet", 0);
+       io->u.sAMAccountName            = samdb_result_string(searched_msg, "sAMAccountName", NULL);
+       io->u.user_principal_name       = samdb_result_string(searched_msg, "userPrincipalName", NULL);
+       io->u.is_computer               = ldb_msg_check_string_attribute(searched_msg, "objectClass", "computer");
+
+       if (io->u.sAMAccountName == NULL) {
+               ldb_asprintf_errstring(ldb,
+                                      "setup_io: sAMAccountName attribute is missing on %s for attempted password set/change",
+                                      ldb_dn_get_linearized(searched_msg->dn));
+
+               return LDB_ERR_CONSTRAINT_VIOLATION;
+       }
+
+       /* Only non-trust accounts have restrictions (possibly this test is the
+        * wrong way around, but we like to be restrictive if possible */
+       io->u.restrictions = !(io->u.userAccountControl
+               & (UF_INTERDOMAIN_TRUST_ACCOUNT | UF_WORKSTATION_TRUST_ACCOUNT
+                       | UF_SERVER_TRUST_ACCOUNT));
+
+       if ((io->u.userAccountControl & UF_PASSWD_NOTREQD) != 0) {
+               /* see [MS-ADTS] 2.2.15 */
+               io->u.restrictions = 0;
+       }
+
+       ret = samdb_msg_find_old_and_new_ldb_val(orig_msg, "userPassword",
+               &io->n.cleartext_utf8, &io->og.cleartext_utf8);
+       if (ret != LDB_SUCCESS) {
+               ldb_asprintf_errstring(ldb,
+                       "setup_io: "
+                       "it's only allowed to set the old password once!");
+               return ret;
+       }
+
+       ret = samdb_msg_find_old_and_new_ldb_val(orig_msg, "clearTextPassword",
+               &io->n.cleartext_utf16, &io->og.cleartext_utf16);
+       if (ret != LDB_SUCCESS) {
+               ldb_asprintf_errstring(ldb,
+                       "setup_io: "
+                       "it's only allowed to set the old password once!");
+               return ret;
+       }
+
+       /* this rather strange looking piece of code is there to
+          handle a ldap client setting a password remotely using the
+          unicodePwd ldap field. The syntax is that the password is
+          in UTF-16LE, with a " at either end. Unfortunately the
+          unicodePwd field is also used to store the nt hashes
+          internally in Samba, and is used in the nt hash format on
+          the wire in DRS replication, so we have a single name for
+          two distinct values. The code below leaves us with a small
+          chance (less than 1 in 2^32) of a mixup, if someone manages
+          to create a MD4 hash which starts and ends in 0x22 0x00, as
+          that would then be treated as a UTF16 password rather than
+          a nthash */
+
+       ret = samdb_msg_find_old_and_new_ldb_val(orig_msg, "unicodePwd",
+               &quoted_utf16, &old_quoted_utf16);
+       if (ret != LDB_SUCCESS) {
+               ldb_asprintf_errstring(ldb,
+                       "setup_io: "
+                       "it's only allowed to set the old password once!");
+               return ret;
+       }
+
+       /* Checks and converts the actual "unicodePwd" attribute */
+       if (quoted_utf16 &&
+           quoted_utf16->length >= 4 &&
+           quoted_utf16->data[0] == '"' &&
+           quoted_utf16->data[1] == 0 &&
+           quoted_utf16->data[quoted_utf16->length-2] == '"' &&
+           quoted_utf16->data[quoted_utf16->length-1] == 0) {
+               struct ldb_val *quoted_utf16_2;
+
+               if (io->n.cleartext_utf16) {
+                       /* refuse the change if someone wants to change with
+                          with both UTF16 possibilities at the same time... */
+                       ldb_asprintf_errstring(ldb,
+                               "setup_io: "
+                               "it's only allowed to set the cleartext password as 'unicodePwd' or as 'clearTextPassword'");
+                       return LDB_ERR_UNWILLING_TO_PERFORM;
+               }
+
+               /*
+                * adapt the quoted UTF16 string to be a real
+                * cleartext one
+                */
+               quoted_utf16_2 = talloc(io->ac, struct ldb_val);
+               if (quoted_utf16_2 == NULL) {
+                       ldb_oom(ldb);
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+
+               quoted_utf16_2->data = quoted_utf16->data + 2;
+               quoted_utf16_2->length = quoted_utf16->length-4;
+               io->n.cleartext_utf16 = quoted_utf16_2;
+               io->n.nt_hash = NULL;
+
+       } else if (quoted_utf16) {
+               /* We have only the hash available -> so no plaintext here */
+               if (!ac->hash_values) {
+                       /* refuse the change if someone wants to change
+                          the hash without control specified... */
+                       ldb_asprintf_errstring(ldb,
+                               "setup_io: "
+                               "it's not allowed to set the NT hash password directly'");
+                       /* this looks odd but this is what Windows does:
+                          returns "UNWILLING_TO_PERFORM" on wrong
+                          password sets and "CONSTRAINT_VIOLATION" on
+                          wrong password changes. */
+                       if (old_quoted_utf16 == NULL) {
+                               return LDB_ERR_UNWILLING_TO_PERFORM;
+                       }
+
+                       return LDB_ERR_CONSTRAINT_VIOLATION;
+               }
+
+               io->n.nt_hash = talloc(io->ac, struct samr_Password);
+               memcpy(io->n.nt_hash->hash, quoted_utf16->data,
+                      MIN(quoted_utf16->length, sizeof(io->n.nt_hash->hash)));
+       }
+
+       /* Checks and converts the previous "unicodePwd" attribute */
+       if (old_quoted_utf16 &&
+           old_quoted_utf16->length >= 4 &&
+           old_quoted_utf16->data[0] == '"' &&
+           old_quoted_utf16->data[1] == 0 &&
+           old_quoted_utf16->data[old_quoted_utf16->length-2] == '"' &&
+           old_quoted_utf16->data[old_quoted_utf16->length-1] == 0) {
+               struct ldb_val *old_quoted_utf16_2;
+
+               if (io->og.cleartext_utf16) {
+                       /* refuse the change if someone wants to change with
+                          both UTF16 possibilities at the same time... */
+                       ldb_asprintf_errstring(ldb,
+                               "setup_io: "
+                               "it's only allowed to set the cleartext password as 'unicodePwd' or as 'clearTextPassword'");
+                       return LDB_ERR_UNWILLING_TO_PERFORM;
+               }
+
+               /*
+                * adapt the quoted UTF16 string to be a real
+                * cleartext one
+                */
+               old_quoted_utf16_2 = talloc(io->ac, struct ldb_val);
+               if (old_quoted_utf16_2 == NULL) {
+                       ldb_oom(ldb);
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+
+               old_quoted_utf16_2->data = old_quoted_utf16->data + 2;
+               old_quoted_utf16_2->length = old_quoted_utf16->length-4;
+
+               io->og.cleartext_utf16 = old_quoted_utf16_2;
+               io->og.nt_hash = NULL;
+       } else if (old_quoted_utf16) {
+               /* We have only the hash available -> so no plaintext here */
+               if (!ac->hash_values) {
+                       /* refuse the change if someone wants to change
+                          the hash without control specified... */
+                       ldb_asprintf_errstring(ldb,
+                               "setup_io: "
+                               "it's not allowed to set the NT hash password directly'");
+                       return LDB_ERR_UNWILLING_TO_PERFORM;
+               }
+
+               io->og.nt_hash = talloc(io->ac, struct samr_Password);
+               memcpy(io->og.nt_hash->hash, old_quoted_utf16->data,
+                      MIN(old_quoted_utf16->length, sizeof(io->og.nt_hash->hash)));
+       }
+
+       /* Handles the "dBCSPwd" attribute (LM hash) */
+       io->n.lm_hash = NULL; io->og.lm_hash = NULL;
+       ret = samdb_msg_find_old_and_new_ldb_val(orig_msg, "dBCSPwd",
+               &lm_hash, &old_lm_hash);
+       if (ret != LDB_SUCCESS) {
+               ldb_asprintf_errstring(ldb,
+                       "setup_io: "
+                       "it's only allowed to set the old password once!");
+               return ret;
+       }
+
+       if (((lm_hash != NULL) || (old_lm_hash != NULL)) && (!ac->hash_values)) {
+               /* refuse the change if someone wants to change the hash
+                  without control specified... */
+               ldb_asprintf_errstring(ldb,
+                       "setup_io: "
+                       "it's not allowed to set the LM hash password directly'");
+               return LDB_ERR_UNWILLING_TO_PERFORM;
+       }
+       if (lm_hash != NULL) {
+               io->n.lm_hash = talloc(io->ac, struct samr_Password);
+               memcpy(io->n.lm_hash->hash, lm_hash->data, MIN(lm_hash->length,
+                      sizeof(io->n.lm_hash->hash)));
+       }
+
+       if (old_lm_hash != NULL) {
+               io->og.lm_hash = talloc(io->ac, struct samr_Password);
+               memcpy(io->og.lm_hash->hash, old_lm_hash->data, MIN(old_lm_hash->length,
+                      sizeof(io->og.lm_hash->hash)));
+       }
+
+       /* refuse the change if someone wants to change the clear-
+          text and supply his own hashes at the same time... */
+       if ((io->n.cleartext_utf8 || io->n.cleartext_utf16)
+                       && (io->n.nt_hash || io->n.lm_hash)) {
+               ldb_asprintf_errstring(ldb,
+                       "setup_io: "
+                       "it's only allowed to set the password in form of cleartext attributes or as hashes");
+               return LDB_ERR_UNWILLING_TO_PERFORM;
+       }
+
+       /* refuse the change if someone wants to change the password
+          using both plaintext methods (UTF8 and UTF16) at the same time... */
+       if (io->n.cleartext_utf8 && io->n.cleartext_utf16) {
+               ldb_asprintf_errstring(ldb,
+                       "setup_io: "
+                       "it's only allowed to set the cleartext password as 'unicodePwd' or as 'userPassword' or as 'clearTextPassword'");
+               return LDB_ERR_UNWILLING_TO_PERFORM;
+       }
+
+       /* refuse the change if someone wants to compare against a plaintext
+          or hash at the same time for a "password modify" operation... */
+       if ((io->og.cleartext_utf8 || io->og.cleartext_utf16)
+           && (io->og.nt_hash || io->og.lm_hash)) {
+               ldb_asprintf_errstring(ldb,
+                       "setup_io: "
+                       "it's only allowed to provide the old password in form of cleartext attributes or as hashes");
+               return LDB_ERR_UNWILLING_TO_PERFORM;
+       }
+
+       /* refuse the change if someone wants to compare against both
+        * plaintexts at the same time for a "password modify" operation... */
+       if (io->og.cleartext_utf8 && io->og.cleartext_utf16) {
+               ldb_asprintf_errstring(ldb,
+                       "setup_io: "
+                       "it's only allowed to provide the old cleartext password as 'unicodePwd' or as 'userPassword' or as 'clearTextPassword'");
+               return LDB_ERR_UNWILLING_TO_PERFORM;
+       }
+
+       /* refuse the change if someone wants to compare against both
+        * hashes at the same time for a "password modify" operation... */
+       if (io->og.nt_hash && io->og.lm_hash) {
+               ldb_asprintf_errstring(ldb,
+                       "setup_io: "
+                       "it's only allowed to provide the old password in hash format as 'unicodePwd' or as 'dBCSPwd'");
+               return LDB_ERR_UNWILLING_TO_PERFORM;
+       }
+
+       /* Decides if we have a password modify or password reset operation */
+       if (ac->req->operation == LDB_ADD) {
+               /* On "add" we have only "password reset" */
+               ac->pwd_reset = true;
+       } else if (ac->req->operation == LDB_MODIFY) {
+               if (io->og.cleartext_utf8 || io->og.cleartext_utf16
+                   || io->og.nt_hash || io->og.lm_hash
+                   || ac->change_old_pw_checked) {
+                       /* If we have an old password or the "change old
+                        * password checked" control specified then for sure it
+                        * is a user "password change" */
+                       ac->pwd_reset = false;
+               } else {
+                       /* Otherwise we have also here a "password reset" */
+                       ac->pwd_reset = true;
+               }
+       } else {
+               /* this shouldn't happen */
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       ac->dom_req->op.search.attrs = attrs;
-       ac->dom_req->controls = NULL;
-       ac->dom_req->context = ac;
-       ac->dom_req->callback = get_domain_data_callback;
-       ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->dom_req);
 
        return LDB_SUCCESS;
 }
 
-static struct domain_data *get_domain_data(struct ldb_module *module, void *ctx, struct ldb_reply *res)
+static struct ph_context *ph_init_context(struct ldb_module *module,
+                                         struct ldb_request *req)
 {
-       struct domain_data *data;
-       const char *tmp;
+       struct ldb_context *ldb;
        struct ph_context *ac;
-       char *p;
 
-       ac = talloc_get_type(ctx, struct ph_context);
+       ldb = ldb_module_get_ctx(module);
 
-       data = talloc_zero(ac, struct domain_data);
-       if (data == NULL) {
+       ac = talloc_zero(req, struct ph_context);
+       if (ac == NULL) {
+               ldb_set_errstring(ldb, "Out of Memory");
                return NULL;
        }
 
-       if (res == NULL) {
-               ldb_debug(module->ldb, LDB_DEBUG_ERROR, "Could not find this user's domain: %s!\n", dom_sid_string(data, ac->domain_sid));
-               talloc_free(data);
-               return NULL;
+       ac->module = module;
+       ac->req = req;
+
+       return ac;
+}
+
+static void ph_apply_controls(struct ph_context *ac)
+{
+       struct ldb_control *ctrl;
+
+       ac->change_status = false;
+       ctrl = ldb_request_get_control(ac->req,
+                                      DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID);
+       if (ctrl != NULL) {
+               ac->change_status = true;
+
+               /* Mark the "change status" control as uncritical (done) */
+               ctrl->critical = false;
        }
 
-       data->pwdProperties= samdb_result_uint(res->message, "pwdProperties", 0);
-       data->store_cleartext = data->pwdProperties & DOMAIN_PASSWORD_STORE_CLEARTEXT;
-       data->pwdHistoryLength = samdb_result_uint(res->message, "pwdHistoryLength", 0);
+       ac->hash_values = false;
+       ctrl = ldb_request_get_control(ac->req,
+                                      DSDB_CONTROL_PASSWORD_HASH_VALUES_OID);
+       if (ctrl != NULL) {
+               ac->hash_values = true;
 
-       /* For a domain DN, this puts things in dotted notation */
-       /* For builtin domains, this will give details for the host,
-        * but that doesn't really matter, as it's just used for salt
-        * and kerberos principals, which don't exist here */
+               /* Mark the "hash values" control as uncritical (done) */
+               ctrl->critical = false;
+       }
 
-       tmp = ldb_dn_canonical_string(ctx, res->message->dn);
-       if (!tmp) {
-               return NULL;
+       ac->change_old_pw_checked = false;
+       ctrl = ldb_request_get_control(ac->req,
+                                      DSDB_CONTROL_PASSWORD_CHANGE_OLD_PW_CHECKED_OID);
+       if (ctrl != NULL) {
+               ac->change_old_pw_checked = true;
+
+               /* Mark the "change old password checked" control as uncritical
+                * (done) */
+               ctrl->critical = false;
        }
-       
-       /* But it puts a trailing (or just before 'builtin') / on things, so kill that */
-       p = strchr(tmp, '/');
-       if (p) {
-               p[0] = '\0';
+}
+
+static int ph_op_callback(struct ldb_request *req, struct ldb_reply *ares)
+{
+       struct ph_context *ac;
+
+       ac = talloc_get_type(req->context, struct ph_context);
+
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+
+       if (ares->type == LDB_REPLY_REFERRAL) {
+               return ldb_module_send_referral(ac->req, ares->referral);
+       }
+
+       if ((ares->error != LDB_ERR_OPERATIONS_ERROR) && (ac->change_status)) {
+               /* On success and trivial errors a status control is being
+                * added (used for example by the "samdb_set_password" call) */
+               ldb_reply_add_control(ares,
+                                     DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID,
+                                     false,
+                                     ac->status);
+       }
+
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
        }
 
-       if (tmp != NULL) {
-               data->dns_domain = strlower_talloc(data, tmp);
-               if (data->dns_domain == NULL) {
-                       ldb_debug(module->ldb, LDB_DEBUG_ERROR, "Out of memory!\n");
-                       return NULL;
+       if (ares->type != LDB_REPLY_DONE) {
+               talloc_free(ares);
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+
+       return ldb_module_done(ac->req, ares->controls,
+                               ares->response, ares->error);
+}
+
+static int password_hash_add_do_add(struct ph_context *ac);
+static int ph_modify_callback(struct ldb_request *req, struct ldb_reply *ares);
+static int password_hash_mod_search_self(struct ph_context *ac);
+static int ph_mod_search_callback(struct ldb_request *req, struct ldb_reply *ares);
+static int password_hash_mod_do_mod(struct ph_context *ac);
+
+static int get_domain_data_callback(struct ldb_request *req,
+                                   struct ldb_reply *ares)
+{
+       struct ldb_context *ldb;
+       struct ph_context *ac;
+       struct loadparm_context *lp_ctx;
+       int ret;
+
+       ac = talloc_get_type(req->context, struct ph_context);
+       ldb = ldb_module_get_ctx(ac->module);
+
+       if (!ares) {
+               ret = LDB_ERR_OPERATIONS_ERROR;
+               goto done;
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
+               if (ac->status != NULL) {
+                       talloc_free(ares);
+
+                       ldb_set_errstring(ldb, "Too many results");
+                       ret = LDB_ERR_OPERATIONS_ERROR;
+                       goto done;
                }
-               data->realm = strupper_talloc(data, tmp);
-               if (data->realm == NULL) {
-                       ldb_debug(module->ldb, LDB_DEBUG_ERROR, "Out of memory!\n");
-                       return NULL;
+
+               /* Setup the "status" structure (used as control later) */
+               ac->status = talloc_zero(ac->req,
+                                        struct dsdb_control_password_change_status);
+               if (ac->status == NULL) {
+                       talloc_free(ares);
+
+                       ldb_oom(ldb);
+                       ret = LDB_ERR_OPERATIONS_ERROR;
+                       goto done;
                }
-               p = strchr(tmp, '.');
-               if (p) {
-                       p[0] = '\0';
+
+               /* Setup the "domain data" structure */
+               ac->status->domain_data.pwdProperties = samdb_result_uint(ares->message, "pwdProperties", -1);
+               ac->status->domain_data.pwdHistoryLength = samdb_result_uint(ares->message, "pwdHistoryLength", -1);
+               ac->status->domain_data.maxPwdAge = samdb_result_int64(ares->message, "maxPwdAge", -1);
+               ac->status->domain_data.minPwdAge = samdb_result_int64(ares->message, "minPwdAge", -1);
+               ac->status->domain_data.minPwdLength = samdb_result_uint(ares->message, "minPwdLength", -1);
+               ac->status->domain_data.store_cleartext =
+                       ac->status->domain_data.pwdProperties & DOMAIN_PASSWORD_STORE_CLEARTEXT;
+
+               talloc_free(ares);
+
+               /* For a domain DN, this puts things in dotted notation */
+               /* For builtin domains, this will give details for the host,
+                * but that doesn't really matter, as it's just used for salt
+                * and kerberos principals, which don't exist here */
+
+               lp_ctx = talloc_get_type(ldb_get_opaque(ldb, "loadparm"),
+                                        struct loadparm_context);
+
+               ac->status->domain_data.dns_domain = lp_dnsdomain(lp_ctx);
+               ac->status->domain_data.realm = lp_realm(lp_ctx);
+               ac->status->domain_data.netbios_domain = lp_sam_name(lp_ctx);
+
+               ac->status->reject_reason = SAM_PWD_CHANGE_NO_ERROR;
+
+               ret = LDB_SUCCESS;
+               break;
+
+       case LDB_REPLY_REFERRAL:
+               /* ignore */
+               talloc_free(ares);
+               ret = LDB_SUCCESS;
+               break;
+
+       case LDB_REPLY_DONE:
+               talloc_free(ares);
+               /* call the next step */
+               switch (ac->req->operation) {
+               case LDB_ADD:
+                       ret = password_hash_add_do_add(ac);
+                       break;
+
+               case LDB_MODIFY:
+                       ret = password_hash_mod_do_mod(ac);
+                       break;
+
+               default:
+                       ret = LDB_ERR_OPERATIONS_ERROR;
+                       break;
                }
-               data->netbios_domain = strupper_talloc(data, tmp);
-               if (data->netbios_domain == NULL) {
-                       ldb_debug(module->ldb, LDB_DEBUG_ERROR, "Out of memory!\n");
-                       return NULL;
+               break;
+       }
+
+done:
+       if (ret != LDB_SUCCESS) {
+               struct ldb_reply *new_ares;
+
+               new_ares = talloc_zero(ac->req, struct ldb_reply);
+               if (new_ares == NULL) {
+                       ldb_oom(ldb);
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                              LDB_ERR_OPERATIONS_ERROR);
                }
+
+               new_ares->error = ret;
+               if ((ret != LDB_ERR_OPERATIONS_ERROR) && (ac->change_status)) {
+                       /* On success and trivial errors a status control is being
+                        * added (used for example by the "samdb_set_password" call) */
+                       ldb_reply_add_control(new_ares,
+                                             DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID,
+                                             false,
+                                             ac->status);
+               }
+
+               return ldb_module_done(ac->req, new_ares->controls,
+                                      new_ares->response, new_ares->error);
        }
 
-       return data;
+       return LDB_SUCCESS;
+}
+
+static int build_domain_data_request(struct ph_context *ac)
+{
+       /* attrs[] is returned from this function in
+          ac->dom_req->op.search.attrs, so it must be static, as
+          otherwise the compiler can put it on the stack */
+       struct ldb_context *ldb;
+       static const char * const attrs[] = { "pwdProperties",
+                                             "pwdHistoryLength",
+                                             "maxPwdAge",
+                                             "minPwdAge",
+                                             "minPwdLength",
+                                             NULL };
+
+       ldb = ldb_module_get_ctx(ac->module);
+
+       return ldb_build_search_req(&ac->dom_req, ldb, ac,
+                                   ldb_get_default_basedn(ldb),
+                                   LDB_SCOPE_BASE,
+                                   NULL, attrs,
+                                   NULL,
+                                   ac, get_domain_data_callback,
+                                   ac->req);
 }
 
 static int password_hash_add(struct ldb_module *module, struct ldb_request *req)
 {
-       struct ldb_handle *h;
+       struct ldb_context *ldb;
        struct ph_context *ac;
-       struct ldb_message_element *sambaAttr;
-       struct ldb_message_element *ntAttr;
-       struct ldb_message_element *lmAttr;
+       struct ldb_message_element *userPasswordAttr, *clearTextPasswordAttr,
+               *ntAttr, *lmAttr;
        int ret;
 
-       ldb_debug(module->ldb, LDB_DEBUG_TRACE, "password_hash_add\n");
+       ldb = ldb_module_get_ctx(module);
+
+       ldb_debug(ldb, LDB_DEBUG_TRACE, "password_hash_add\n");
 
        if (ldb_dn_is_special(req->op.add.message->dn)) { /* do not manipulate our control entries */
                return ldb_next_request(module, req);
        }
 
        /* If the caller is manipulating the local passwords directly, let them pass */
-       if (ldb_dn_compare_base(ldb_dn_new(req, module->ldb, LOCAL_BASE),
+       if (ldb_dn_compare_base(ldb_dn_new(req, ldb, LOCAL_BASE),
                                req->op.add.message->dn) == 0) {
                return ldb_next_request(module, req);
        }
 
-       /* nobody must touch this fields */
+       /* nobody must touch password histories and 'supplementalCredentials' */
        if (ldb_msg_find_element(req->op.add.message, "ntPwdHistory")) {
                return LDB_ERR_UNWILLING_TO_PERFORM;
        }
@@ -1331,150 +2214,107 @@ static int password_hash_add(struct ldb_module *module, struct ldb_request *req)
                return LDB_ERR_UNWILLING_TO_PERFORM;
        }
 
-       /* If no part of this ADD touches the userPassword, or the NT
-        * or LM hashes, then we don't need to make any changes.  */
+       /* If no part of this touches the 'userPassword' OR 'clearTextPassword'
+        * OR 'unicodePwd' OR 'dBCSPwd' we don't need to make any changes. */
 
-       sambaAttr = ldb_msg_find_element(req->op.mod.message, "userPassword");
-       ntAttr = ldb_msg_find_element(req->op.mod.message, "unicodePwd");
-       lmAttr = ldb_msg_find_element(req->op.mod.message, "dBCSPwd");
+       userPasswordAttr = ldb_msg_find_element(req->op.add.message, "userPassword");
+       clearTextPasswordAttr = ldb_msg_find_element(req->op.add.message, "clearTextPassword");
+       ntAttr = ldb_msg_find_element(req->op.add.message, "unicodePwd");
+       lmAttr = ldb_msg_find_element(req->op.add.message, "dBCSPwd");
 
-       if ((!sambaAttr) && (!ntAttr) && (!lmAttr)) {
+       if ((!userPasswordAttr) && (!clearTextPasswordAttr) && (!ntAttr) && (!lmAttr)) {
                return ldb_next_request(module, req);
        }
 
-       /* if it is not an entry of type person its an error */
-       /* TODO: remove this when userPassword will be in schema */
-       if (!ldb_msg_check_string_attribute(req->op.add.message, "objectClass", "person")) {
-               ldb_set_errstring(module->ldb, "Cannot set a password on entry that does not have objectClass 'person'");
-               return LDB_ERR_OBJECT_CLASS_VIOLATION;
-       }
-
-       /* check userPassword is single valued here */
-       /* TODO: remove this when userPassword will be single valued in schema */
-       if (sambaAttr && sambaAttr->num_values > 1) {
-               ldb_set_errstring(module->ldb, "mupltiple values for userPassword not allowed!\n");
-               return LDB_ERR_CONSTRAINT_VIOLATION;
-       }
-
-       if (ntAttr && (ntAttr->num_values > 1)) {
-               ldb_set_errstring(module->ldb, "mupltiple values for unicodePwd not allowed!\n");
-               return LDB_ERR_CONSTRAINT_VIOLATION;
-       }
-       if (lmAttr && (lmAttr->num_values > 1)) {
-               ldb_set_errstring(module->ldb, "mupltiple values for dBCSPwd not allowed!\n");
-               return LDB_ERR_CONSTRAINT_VIOLATION;
-       }
+       /* Make sure we are performing the password set action on a (for us)
+        * valid object. Those are instances of either "user" and/or
+        * "inetOrgPerson". Otherwise continue with the submodules. */
+       if ((!ldb_msg_check_string_attribute(req->op.add.message, "objectClass", "user"))
+               && (!ldb_msg_check_string_attribute(req->op.add.message, "objectClass", "inetOrgPerson"))) {
 
-       if (sambaAttr && sambaAttr->num_values == 0) {
-               ldb_set_errstring(module->ldb, "userPassword must have a value!\n");
-               return LDB_ERR_CONSTRAINT_VIOLATION;
-       }
+               if (ldb_msg_find_element(req->op.add.message, "clearTextPassword") != NULL) {
+                       ldb_set_errstring(ldb,
+                                         "'clearTextPassword' is only allowed on objects of class 'user' and/or 'inetOrgPerson'!");
+                       return LDB_ERR_NO_SUCH_ATTRIBUTE;
+               }
 
-       if (ntAttr && (ntAttr->num_values == 0)) {
-               ldb_set_errstring(module->ldb, "unicodePwd must have a value!\n");
-               return LDB_ERR_CONSTRAINT_VIOLATION;
-       }
-       if (lmAttr && (lmAttr->num_values == 0)) {
-               ldb_set_errstring(module->ldb, "dBCSPwd must have a value!\n");
-               return LDB_ERR_CONSTRAINT_VIOLATION;
+               return ldb_next_request(module, req);
        }
 
-       h = ph_init_handle(req, module, PH_ADD);
-       if (!h) {
+       ac = ph_init_context(module, req);
+       if (ac == NULL) {
+               DEBUG(0,(__location__ ": %s\n", ldb_errstring(ldb)));
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       ac = talloc_get_type(h->private_data, struct ph_context);
+       ph_apply_controls(ac);
 
        /* get user domain data */
-       ac->domain_sid = samdb_result_sid_prefix(ac, req->op.add.message, "objectSid");
-       if (ac->domain_sid == NULL) {
-               ldb_debug(module->ldb, LDB_DEBUG_ERROR, "can't handle entry with missing objectSid!\n");
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
        ret = build_domain_data_request(ac);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
 
-       ac->step = PH_ADD_SEARCH_DOM;
-
-       req->handle = h;
-
        return ldb_next_request(module, ac->dom_req);
 }
 
-static int password_hash_add_do_add(struct ldb_handle *h) {
-
-       struct ph_context *ac;
-       struct domain_data *domain;
-       struct smb_krb5_context *smb_krb5_context;
+static int password_hash_add_do_add(struct ph_context *ac)
+{
+       struct ldb_context *ldb;
+       struct ldb_request *down_req;
        struct ldb_message *msg;
        struct setup_password_fields_io io;
        int ret;
 
-       ac = talloc_get_type(h->private_data, struct ph_context);
-
-       domain = get_domain_data(ac->module, ac, ac->dom_res);
-       if (domain == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
+       /* Prepare the internal data structure containing the passwords */
+       ret = setup_io(ac, ac->req->op.add.message, ac->req->op.add.message, &io);
+       if (ret != LDB_SUCCESS) {
+               return ret;
        }
 
-       ac->down_req = talloc(ac, struct ldb_request);
-       if (ac->down_req == NULL) {
+       msg = ldb_msg_copy_shallow(ac, ac->req->op.add.message);
+       if (msg == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       *(ac->down_req) = *(ac->orig_req);
-       ac->down_req->op.add.message = msg = ldb_msg_copy_shallow(ac->down_req, ac->orig_req->op.add.message);
-       if (ac->down_req->op.add.message == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
+       /* remove attributes that we just read into 'io' (handle also superfluous
+        * "password modify" trials - multiple attributes with the same name -
+        * on add operations) */
+       while (ldb_msg_find_element(msg, "userPassword") != NULL) {
+               ldb_msg_remove_attr(msg, "userPassword");
        }
-
-       /* Some operations below require kerberos contexts */
-       if (smb_krb5_init_context(ac->down_req, 
-                                 ldb_get_opaque(h->module->ldb, "EventContext"), 
-                                 (struct loadparm_context *)ldb_get_opaque(h->module->ldb, "loadparm"), 
-                                 &smb_krb5_context) != 0) {
-               return LDB_ERR_OPERATIONS_ERROR;
+       while (ldb_msg_find_element(msg, "clearTextPassword") != NULL) {
+               ldb_msg_remove_attr(msg, "clearTextPassword");
+       }
+       while (ldb_msg_find_element(msg, "unicodePwd") != NULL) {
+               ldb_msg_remove_attr(msg, "unicodePwd");
+       }
+       while (ldb_msg_find_element(msg, "dBCSPwd") != NULL) {
+               ldb_msg_remove_attr(msg, "dBCSPwd");
        }
 
-       ZERO_STRUCT(io);
-       io.ac                           = ac;
-       io.domain                       = domain;
-       io.smb_krb5_context             = smb_krb5_context;
-
-       io.u.user_account_control       = samdb_result_uint(msg, "userAccountControl", 0);
-       io.u.sAMAccountName             = samdb_result_string(msg, "samAccountName", NULL);
-       io.u.user_principal_name        = samdb_result_string(msg, "userPrincipalName", NULL);
-       io.u.is_computer                = ldb_msg_check_string_attribute(msg, "objectClass", "computer");
-
-       io.n.cleartext                  = samdb_result_string(msg, "userPassword", NULL);
-       io.n.nt_hash                    = samdb_result_hash(io.ac, msg, "unicodePwd");
-       io.n.lm_hash                    = samdb_result_hash(io.ac, msg, "dBCSPwd");
-
-       /* remove attributes */
-       if (io.n.cleartext) ldb_msg_remove_attr(msg, "userPassword");
-       if (io.n.nt_hash) ldb_msg_remove_attr(msg, "unicodePwd");
-       if (io.n.lm_hash) ldb_msg_remove_attr(msg, "dBCSPwd");
        ldb_msg_remove_attr(msg, "pwdLastSet");
-       io.o.kvno = samdb_result_uint(msg, "msDs-KeyVersionNumber", 1) - 1;
-       ldb_msg_remove_attr(msg, "msDs-KeyVersionNumber");
+
+       ldb = ldb_module_get_ctx(ac->module);
 
        ret = setup_password_fields(&io);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
 
+       ret = check_password_restrictions(&io);
+       if (ret != LDB_SUCCESS) {
+               return ret;
+       }
+
        if (io.g.nt_hash) {
-               ret = samdb_msg_add_hash(ac->module->ldb, ac, msg,
+               ret = samdb_msg_add_hash(ldb, ac, msg,
                                         "unicodePwd", io.g.nt_hash);
                if (ret != LDB_SUCCESS) {
                        return ret;
                }
        }
        if (io.g.lm_hash) {
-               ret = samdb_msg_add_hash(ac->module->ldb, ac, msg,
+               ret = samdb_msg_add_hash(ldb, ac, msg,
                                         "dBCSPwd", io.g.lm_hash);
                if (ret != LDB_SUCCESS) {
                        return ret;
@@ -1505,286 +2345,353 @@ static int password_hash_add_do_add(struct ldb_handle *h) {
                        return ret;
                }
        }
-       ret = samdb_msg_add_uint64(ac->module->ldb, ac, msg,
+       ret = samdb_msg_add_uint64(ldb, ac, msg,
                                   "pwdLastSet",
                                   io.g.last_set);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
-       ret = samdb_msg_add_uint(ac->module->ldb, ac, msg,
-                                "msDs-KeyVersionNumber",
-                                io.g.kvno);
+
+       ret = ldb_build_add_req(&down_req, ldb, ac,
+                               msg,
+                               ac->req->controls,
+                               ac, ph_op_callback,
+                               ac->req);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
 
-       h->state = LDB_ASYNC_INIT;
-       h->status = LDB_SUCCESS;
-
-       ac->step = PH_ADD_DO_ADD;
-
-       ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->down_req);
-
-       /* perform the operation */
-       return ldb_next_request(ac->module, ac->down_req);
+       return ldb_next_request(ac->module, down_req);
 }
 
-static int password_hash_mod_search_self(struct ldb_handle *h);
-
 static int password_hash_modify(struct ldb_module *module, struct ldb_request *req)
 {
-       struct ldb_handle *h;
+       struct ldb_context *ldb;
        struct ph_context *ac;
-       struct ldb_message_element *sambaAttr;
-       struct ldb_message_element *ntAttr;
-       struct ldb_message_element *lmAttr;
+       const char *passwordAttrs[] = { "userPassword", "clearTextPassword",
+               "unicodePwd", "dBCSPwd", NULL }, **l;
+       unsigned int attr_cnt, del_attr_cnt, add_attr_cnt, rep_attr_cnt;
+       struct ldb_message_element *passwordAttr;
        struct ldb_message *msg;
+       struct ldb_request *down_req;
+       int ret;
 
-       ldb_debug(module->ldb, LDB_DEBUG_TRACE, "password_hash_modify\n");
+       ldb = ldb_module_get_ctx(module);
+
+       ldb_debug(ldb, LDB_DEBUG_TRACE, "password_hash_modify\n");
 
        if (ldb_dn_is_special(req->op.mod.message->dn)) { /* do not manipulate our control entries */
                return ldb_next_request(module, req);
        }
        
        /* If the caller is manipulating the local passwords directly, let them pass */
-       if (ldb_dn_compare_base(ldb_dn_new(req, module->ldb, LOCAL_BASE),
+       if (ldb_dn_compare_base(ldb_dn_new(req, ldb, LOCAL_BASE),
                                req->op.mod.message->dn) == 0) {
                return ldb_next_request(module, req);
        }
 
-       /* nobody must touch password Histories */
-       if (ldb_msg_find_element(req->op.add.message, "ntPwdHistory")) {
+       /* nobody must touch password histories and 'supplementalCredentials' */
+       if (ldb_msg_find_element(req->op.mod.message, "ntPwdHistory")) {
                return LDB_ERR_UNWILLING_TO_PERFORM;
        }
-       if (ldb_msg_find_element(req->op.add.message, "lmPwdHistory")) {
+       if (ldb_msg_find_element(req->op.mod.message, "lmPwdHistory")) {
                return LDB_ERR_UNWILLING_TO_PERFORM;
        }
-       if (ldb_msg_find_element(req->op.add.message, "supplementalCredentials")) {
+       if (ldb_msg_find_element(req->op.mod.message, "supplementalCredentials")) {
                return LDB_ERR_UNWILLING_TO_PERFORM;
        }
 
-       sambaAttr = ldb_msg_find_element(req->op.mod.message, "userPassword");
-       ntAttr = ldb_msg_find_element(req->op.mod.message, "unicodePwd");
-       lmAttr = ldb_msg_find_element(req->op.mod.message, "dBCSPwd");
-
-       /* If no part of this touches the userPassword OR unicodePwd and/or dBCSPwd, then we don't
-        * need to make any changes.  For password changes/set there should
-        * be a 'delete' or a 'modify' on this attribute. */
-       if ((!sambaAttr) && (!ntAttr) && (!lmAttr)) {
+       /* If no part of this touches the 'userPassword' OR 'clearTextPassword'
+        * OR 'unicodePwd' OR 'dBCSPwd' we don't need to make any changes.
+        * For password changes/set there should be a 'delete' or a 'modify'
+        * on these attributes. */
+       attr_cnt = 0;
+       for (l = passwordAttrs; *l != NULL; l++) {
+               if (ldb_msg_find_element(req->op.mod.message, *l) != NULL) {
+                       ++attr_cnt;
+               }
+       }
+       if (attr_cnt == 0) {
                return ldb_next_request(module, req);
        }
 
-       /* check passwords are single valued here */
-       /* TODO: remove this when passwords will be single valued in schema */
-       if (sambaAttr && (sambaAttr->num_values > 1)) {
-               return LDB_ERR_CONSTRAINT_VIOLATION;
+       ac = ph_init_context(module, req);
+       if (!ac) {
+               DEBUG(0,(__location__ ": %s\n", ldb_errstring(ldb)));
+               return LDB_ERR_OPERATIONS_ERROR;
        }
-       if (ntAttr && (ntAttr->num_values > 1)) {
-               return LDB_ERR_CONSTRAINT_VIOLATION;
+       ph_apply_controls(ac);
+
+       /* use a new message structure so that we can modify it */
+       msg = ldb_msg_copy_shallow(ac, req->op.mod.message);
+       if (msg == NULL) {
+               ldb_oom(ldb);
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       /* - check for single-valued password attributes
+        *   (if not return "CONSTRAINT_VIOLATION")
+        * - check that for a password change operation one add and one delete
+        *   operation exists
+        *   (if not return "CONSTRAINT_VIOLATION" or "UNWILLING_TO_PERFORM")
+        * - check that a password change and a password set operation cannot
+        *   be mixed
+        *   (if not return "UNWILLING_TO_PERFORM")
+        * - remove all password attributes modifications from the first change
+        *   operation (anything without the passwords) - we will make the real
+        *   modification later */
+       del_attr_cnt = 0;
+       add_attr_cnt = 0;
+       rep_attr_cnt = 0;
+       for (l = passwordAttrs; *l != NULL; l++) {
+               while ((passwordAttr = ldb_msg_find_element(msg, *l)) != NULL) {
+                       if (passwordAttr->flags == LDB_FLAG_MOD_DELETE) {
+                               ++del_attr_cnt;
+                       }
+                       if (passwordAttr->flags == LDB_FLAG_MOD_ADD) {
+                               ++add_attr_cnt;
+                       }
+                       if (passwordAttr->flags == LDB_FLAG_MOD_REPLACE) {
+                               ++rep_attr_cnt;
+                       }
+                       if ((passwordAttr->num_values != 1) &&
+                           (passwordAttr->flags != LDB_FLAG_MOD_REPLACE)) {
+                               talloc_free(ac);
+                               ldb_asprintf_errstring(ldb,
+                                                      "'%s' attributes must have exactly one value!",
+                                                      *l);
+                               return LDB_ERR_CONSTRAINT_VIOLATION;
+                       }
+                       ldb_msg_remove_attr(msg, *l);
+               }
        }
-       if (lmAttr && (lmAttr->num_values > 1)) {
+       if ((del_attr_cnt > 0) && (add_attr_cnt == 0)) {
+               talloc_free(ac);
+               ldb_set_errstring(ldb,
+                                 "Only the delete action for a password change specified!");
                return LDB_ERR_CONSTRAINT_VIOLATION;
        }
-
-       h = ph_init_handle(req, module, PH_MOD);
-       if (!h) {
-               return LDB_ERR_OPERATIONS_ERROR;
+       if ((del_attr_cnt == 0) && (add_attr_cnt > 0)) {
+               talloc_free(ac);
+               ldb_set_errstring(ldb,
+                                 "Only the add action for a password change specified!");
+               return LDB_ERR_UNWILLING_TO_PERFORM;
+       }
+       if ((del_attr_cnt > 1) || (add_attr_cnt > 1)) {
+               talloc_free(ac);
+               ldb_set_errstring(ldb,
+                                 "Only one delete and one add action for a password change allowed!");
+               return LDB_ERR_UNWILLING_TO_PERFORM;
+       }
+       if ((rep_attr_cnt > 0) && ((del_attr_cnt > 0) || (add_attr_cnt > 0))) {
+               talloc_free(ac);
+               ldb_set_errstring(ldb,
+                                 "Either a password change or a password set operation is allowed!");
+               return LDB_ERR_UNWILLING_TO_PERFORM;
        }
-       ac = talloc_get_type(h->private_data, struct ph_context);
 
-       /* return or own handle to deal with this call */
-       req->handle = h;
+       /* if there was nothing else to be modified skip to next step */
+       if (msg->num_elements == 0) {
+               return password_hash_mod_search_self(ac);
+       }
 
-       /* prepare the first operation */
-       ac->down_req = talloc_zero(ac, struct ldb_request);
-       if (ac->down_req == NULL) {
-               ldb_set_errstring(module->ldb, "Out of memory!");
-               return LDB_ERR_OPERATIONS_ERROR;
+       ret = ldb_build_mod_req(&down_req, ldb, ac,
+                               msg,
+                               req->controls,
+                               ac, ph_modify_callback,
+                               req);
+       if (ret != LDB_SUCCESS) {
+               return ret;
        }
 
-       *(ac->down_req) = *req; /* copy the request */
+       return ldb_next_request(module, down_req);
+}
 
-       /* use a new message structure so that we can modify it */
-       ac->down_req->op.mod.message = msg = ldb_msg_copy_shallow(ac->down_req, req->op.mod.message);
+static int ph_modify_callback(struct ldb_request *req, struct ldb_reply *ares)
+{
+       struct ph_context *ac;
 
-       /* - remove any imodification to the password from the first commit
-        *   we will make the real modification later */
-       if (sambaAttr) ldb_msg_remove_attr(msg, "userPassword");
-       if (ntAttr) ldb_msg_remove_attr(msg, "unicodePwd");
-       if (lmAttr) ldb_msg_remove_attr(msg, "dBCSPwd");
+       ac = talloc_get_type(req->context, struct ph_context);
 
-       /* if there was nothing else to be modify skip to next step */
-       if (msg->num_elements == 0) {
-               talloc_free(ac->down_req);
-               ac->down_req = NULL;
-               return password_hash_mod_search_self(h);
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
        }
-       
-       ac->down_req->context = NULL;
-       ac->down_req->callback = NULL;
 
-       ac->step = PH_MOD_DO_REQ;
+       if (ares->type == LDB_REPLY_REFERRAL) {
+               return ldb_module_send_referral(ac->req, ares->referral);
+       }
 
-       ldb_set_timeout_from_prev_req(module->ldb, req, ac->down_req);
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
 
-       return ldb_next_request(module, ac->down_req);
+       if (ares->type != LDB_REPLY_DONE) {
+               talloc_free(ares);
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+
+       talloc_free(ares);
+
+       return password_hash_mod_search_self(ac);
 }
 
-static int get_self_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
+static int ph_mod_search_callback(struct ldb_request *req, struct ldb_reply *ares)
 {
+       struct ldb_context *ldb;
        struct ph_context *ac;
+       int ret;
 
-       ac = talloc_get_type(context, struct ph_context);
+       ac = talloc_get_type(req->context, struct ph_context);
+       ldb = ldb_module_get_ctx(ac->module);
 
-       /* we are interested only in the single reply (base search) we receive here */
-       if (ares->type == LDB_REPLY_ENTRY) {
-               if (ac->search_res != NULL) {
-                       ldb_set_errstring(ldb, "Too many results");
+       if (!ares) {
+               ret = LDB_ERR_OPERATIONS_ERROR;
+               goto done;
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       /* we are interested only in the single reply (base search) */
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
+               /* Make sure we are performing the password change action on a
+                * (for us) valid object. Those are instances of either "user"
+                * and/or "inetOrgPerson". Otherwise continue with the
+                * submodules. */
+               if ((!ldb_msg_check_string_attribute(ares->message, "objectClass", "user"))
+                       && (!ldb_msg_check_string_attribute(ares->message, "objectClass", "inetOrgPerson"))) {
                        talloc_free(ares);
-                       return LDB_ERR_OPERATIONS_ERROR;
+
+                       if (ldb_msg_find_element(ac->req->op.mod.message, "clearTextPassword") != NULL) {
+                               ldb_set_errstring(ldb,
+                                                 "'clearTextPassword' is only allowed on objects of class 'user' and/or 'inetOrgPerson'!");
+                               ret = LDB_ERR_NO_SUCH_ATTRIBUTE;
+                               goto done;
+                       }
+
+                       ret = ldb_next_request(ac->module, ac->req);
+                       goto done;
                }
 
-               /* if it is not an entry of type person this is an error */
-               /* TODO: remove this when userPassword will be in schema */
-               if (!ldb_msg_check_string_attribute(ares->message, "objectClass", "person")) {
-                       ldb_set_errstring(ldb, "Object class violation");
+               if (ac->search_res != NULL) {
                        talloc_free(ares);
-                       return LDB_ERR_OBJECT_CLASS_VIOLATION;
+
+                       ldb_set_errstring(ldb, "Too many results");
+                       ret = LDB_ERR_OPERATIONS_ERROR;
+                       goto done;
                }
 
                ac->search_res = talloc_steal(ac, ares);
-       } else {
-               talloc_free(ares);
-       }
-
-       return LDB_SUCCESS;
-}
+               ret = LDB_SUCCESS;
+               break;
 
-static int password_hash_mod_search_self(struct ldb_handle *h) {
+       case LDB_REPLY_REFERRAL:
+               /* ignore anything else for now */
+               talloc_free(ares);
+               ret = LDB_SUCCESS;
+               break;
 
-       struct ph_context *ac;
-       static const char * const attrs[] = { "userAccountControl", "lmPwdHistory", 
-                                             "ntPwdHistory", 
-                                             "objectSid", "msDS-KeyVersionNumber", 
-                                             "objectClass", "userPrincipalName",
-                                             "sAMAccountName", 
-                                             "dBCSPwd", "unicodePwd",
-                                             "supplementalCredentials",
-                                             NULL };
+       case LDB_REPLY_DONE:
+               talloc_free(ares);
 
-       ac = talloc_get_type(h->private_data, struct ph_context);
+               /* get user domain data */
+               ret = build_domain_data_request(ac);
+               if (ret != LDB_SUCCESS) {
+                       return ldb_module_done(ac->req, NULL, NULL, ret);
+               }
 
-       /* prepare the search operation */
-       ac->search_req = talloc_zero(ac, struct ldb_request);
-       if (ac->search_req == NULL) {
-               ldb_debug(ac->module->ldb, LDB_DEBUG_ERROR, "Out of Memory!\n");
-               return LDB_ERR_OPERATIONS_ERROR;
+               ret = ldb_next_request(ac->module, ac->dom_req);
+               break;
        }
 
-       ac->search_req->operation = LDB_SEARCH;
-       ac->search_req->op.search.base = ac->orig_req->op.mod.message->dn;
-       ac->search_req->op.search.scope = LDB_SCOPE_BASE;
-       ac->search_req->op.search.tree = ldb_parse_tree(ac->search_req, NULL);
-       if (ac->search_req->op.search.tree == NULL) {
-               ldb_set_errstring(ac->module->ldb, "Invalid search filter");
-               return LDB_ERR_OPERATIONS_ERROR;
+done:
+       if (ret != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, NULL, NULL, ret);
        }
-       ac->search_req->op.search.attrs = attrs;
-       ac->search_req->controls = NULL;
-       ac->search_req->context = ac;
-       ac->search_req->callback = get_self_callback;
-       ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->search_req);
-
-       ac->step = PH_MOD_SEARCH_SELF;
 
-       return ldb_next_request(ac->module, ac->search_req);
+       return LDB_SUCCESS;
 }
 
-static int password_hash_mod_search_dom(struct ldb_handle *h) {
-
-       struct ph_context *ac;
+static int password_hash_mod_search_self(struct ph_context *ac)
+{
+       struct ldb_context *ldb;
+       static const char * const attrs[] = { "objectClass",
+                                             "userAccountControl",
+                                             "pwdLastSet",
+                                             "sAMAccountName",
+                                             "objectSid",
+                                             "userPrincipalName",
+                                             "supplementalCredentials",
+                                             "lmPwdHistory",
+                                             "ntPwdHistory",
+                                             "dBCSPwd",
+                                             "unicodePwd",
+                                             NULL };
+       struct ldb_request *search_req;
        int ret;
 
-       ac = talloc_get_type(h->private_data, struct ph_context);
+       ldb = ldb_module_get_ctx(ac->module);
 
-       /* get object domain sid */
-       ac->domain_sid = samdb_result_sid_prefix(ac, ac->search_res->message, "objectSid");
-       if (ac->domain_sid == NULL) {
-               ldb_debug(ac->module->ldb, LDB_DEBUG_ERROR, "can't handle entry with missing objectSid!\n");
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
+       ret = ldb_build_search_req(&search_req, ldb, ac,
+                                  ac->req->op.mod.message->dn,
+                                  LDB_SCOPE_BASE,
+                                  "(objectclass=*)",
+                                  attrs,
+                                  NULL,
+                                  ac, ph_mod_search_callback,
+                                  ac->req);
 
-       /* get user domain data */
-       ret = build_domain_data_request(ac);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
 
-       ac->step = PH_MOD_SEARCH_DOM;
-
-       return ldb_next_request(ac->module, ac->dom_req);
+       return ldb_next_request(ac->module, search_req);
 }
 
-static int password_hash_mod_do_mod(struct ldb_handle *h) {
-
-       struct ph_context *ac;
-       struct domain_data *domain;
-       struct smb_krb5_context *smb_krb5_context;
+static int password_hash_mod_do_mod(struct ph_context *ac)
+{
+       struct ldb_context *ldb;
+       struct ldb_request *mod_req;
        struct ldb_message *msg;
-       struct ldb_message *orig_msg;
-       struct ldb_message *searched_msg;
+       const struct ldb_message *orig_msg, *searched_msg;
        struct setup_password_fields_io io;
        int ret;
+       NTSTATUS status;
 
-       ac = talloc_get_type(h->private_data, struct ph_context);
+       ldb = ldb_module_get_ctx(ac->module);
 
-       domain = get_domain_data(ac->module, ac, ac->dom_res);
-       if (domain == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       ac->mod_req = talloc(ac, struct ldb_request);
-       if (ac->mod_req == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       *(ac->mod_req) = *(ac->orig_req);
-       
        /* use a new message structure so that we can modify it */
-       ac->mod_req->op.mod.message = msg = ldb_msg_new(ac->mod_req);
+       msg = ldb_msg_new(ac);
        if (msg == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
        /* modify dn */
-       msg->dn = ac->orig_req->op.mod.message->dn;
+       msg->dn = ac->req->op.mod.message->dn;
 
-       /* Some operations below require kerberos contexts */
-       if (smb_krb5_init_context(ac->mod_req, 
-                                 ldb_get_opaque(h->module->ldb, "EventContext"), 
-                                 (struct loadparm_context *)ldb_get_opaque(h->module->ldb, "loadparm"), 
-                                 &smb_krb5_context) != 0) {
+       orig_msg = ac->req->op.mod.message;
+       searched_msg = ac->search_res->message;
+
+       /* Prepare the internal data structure containing the passwords */
+       ret = setup_io(ac, orig_msg, searched_msg, &io);
+       if (ret != LDB_SUCCESS) {
+               return ret;
+       }
+       
+       /* Get the old password from the database */
+       status = samdb_result_passwords(io.ac,
+                                       ldb_get_opaque(ldb, "loadparm"),
+                                       discard_const_p(struct ldb_message, searched_msg),
+                                       &io.o.lm_hash, &io.o.nt_hash);
+       if (!NT_STATUS_IS_OK(status)) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       orig_msg        = discard_const(ac->orig_req->op.mod.message);
-       searched_msg    = ac->search_res->message;
-
-       ZERO_STRUCT(io);
-       io.ac                           = ac;
-       io.domain                       = domain;
-       io.smb_krb5_context             = smb_krb5_context;
-
-       io.u.user_account_control       = samdb_result_uint(searched_msg, "userAccountControl", 0);
-       io.u.sAMAccountName             = samdb_result_string(searched_msg, "samAccountName", NULL);
-       io.u.user_principal_name        = samdb_result_string(searched_msg, "userPrincipalName", NULL);
-       io.u.is_computer                = ldb_msg_check_string_attribute(searched_msg, "objectClass", "computer");
-
-       io.n.cleartext                  = samdb_result_string(orig_msg, "userPassword", NULL);
-       io.n.nt_hash                    = samdb_result_hash(io.ac, orig_msg, "unicodePwd");
-       io.n.lm_hash                    = samdb_result_hash(io.ac, orig_msg, "dBCSPwd");
-
-       io.o.kvno                       = samdb_result_uint(searched_msg, "msDs-KeyVersionNumber", 0);
        io.o.nt_history_len             = samdb_result_hashes(io.ac, searched_msg, "ntPwdHistory", &io.o.nt_history);
        io.o.lm_history_len             = samdb_result_hashes(io.ac, searched_msg, "lmPwdHistory", &io.o.lm_history);
        io.o.supplemental               = ldb_msg_find_ldb_val(searched_msg, "supplementalCredentials");
@@ -1794,6 +2701,11 @@ static int password_hash_mod_do_mod(struct ldb_handle *h) {
                return ret;
        }
 
+       ret = check_password_restrictions(&io);
+       if (ret != LDB_SUCCESS) {
+               return ret;
+       }
+
        /* make sure we replace all the old attributes */
        ret = ldb_msg_add_empty(msg, "unicodePwd", LDB_FLAG_MOD_REPLACE, NULL);
        ret = ldb_msg_add_empty(msg, "dBCSPwd", LDB_FLAG_MOD_REPLACE, NULL);
@@ -1801,17 +2713,16 @@ static int password_hash_mod_do_mod(struct ldb_handle *h) {
        ret = ldb_msg_add_empty(msg, "lmPwdHistory", LDB_FLAG_MOD_REPLACE, NULL);
        ret = ldb_msg_add_empty(msg, "supplementalCredentials", LDB_FLAG_MOD_REPLACE, NULL);
        ret = ldb_msg_add_empty(msg, "pwdLastSet", LDB_FLAG_MOD_REPLACE, NULL);
-       ret = ldb_msg_add_empty(msg, "msDs-KeyVersionNumber", LDB_FLAG_MOD_REPLACE, NULL);
 
        if (io.g.nt_hash) {
-               ret = samdb_msg_add_hash(ac->module->ldb, ac, msg,
+               ret = samdb_msg_add_hash(ldb, ac, msg,
                                         "unicodePwd", io.g.nt_hash);
                if (ret != LDB_SUCCESS) {
                        return ret;
                }
        }
        if (io.g.lm_hash) {
-               ret = samdb_msg_add_hash(ac->module->ldb, ac, msg,
+               ret = samdb_msg_add_hash(ldb, ac, msg,
                                         "dBCSPwd", io.g.lm_hash);
                if (ret != LDB_SUCCESS) {
                        return ret;
@@ -1842,202 +2753,27 @@ static int password_hash_mod_do_mod(struct ldb_handle *h) {
                        return ret;
                }
        }
-       ret = samdb_msg_add_uint64(ac->module->ldb, ac, msg,
+       ret = samdb_msg_add_uint64(ldb, ac, msg,
                                   "pwdLastSet",
                                   io.g.last_set);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
-       ret = samdb_msg_add_uint(ac->module->ldb, ac, msg,
-                                "msDs-KeyVersionNumber",
-                                io.g.kvno);
+
+       ret = ldb_build_mod_req(&mod_req, ldb, ac,
+                               msg,
+                               ac->req->controls,
+                               ac, ph_op_callback,
+                               ac->req);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
 
-       h->state = LDB_ASYNC_INIT;
-       h->status = LDB_SUCCESS;
-
-       ac->step = PH_MOD_DO_MOD;
-
-       ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->mod_req);
-
-       /* perform the search */
-       return ldb_next_request(ac->module, ac->mod_req);
-}
-
-static int ph_wait(struct ldb_handle *handle) {
-       struct ph_context *ac;
-       int ret;
-    
-       if (!handle || !handle->private_data) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       if (handle->state == LDB_ASYNC_DONE) {
-               return handle->status;
-       }
-
-       handle->state = LDB_ASYNC_PENDING;
-       handle->status = LDB_SUCCESS;
-
-       ac = talloc_get_type(handle->private_data, struct ph_context);
-
-       switch (ac->step) {
-       case PH_ADD_SEARCH_DOM:
-               ret = ldb_wait(ac->dom_req->handle, LDB_WAIT_NONE);
-
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->dom_req->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->dom_req->handle->status;
-                       goto done;
-               }
-
-               if (ac->dom_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-
-               /* domain search done, go on */
-               return password_hash_add_do_add(handle);
-
-       case PH_ADD_DO_ADD:
-               ret = ldb_wait(ac->down_req->handle, LDB_WAIT_NONE);
-
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->down_req->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->down_req->handle->status;
-                       goto done;
-               }
-
-               if (ac->down_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-
-               break;
-               
-       case PH_MOD_DO_REQ:
-               ret = ldb_wait(ac->down_req->handle, LDB_WAIT_NONE);
-
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->down_req->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->down_req->handle->status;
-                       goto done;
-               }
-
-               if (ac->down_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-
-               /* non-password mods done, go on */
-               return password_hash_mod_search_self(handle);
-               
-       case PH_MOD_SEARCH_SELF:
-               ret = ldb_wait(ac->search_req->handle, LDB_WAIT_NONE);
-
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->search_req->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->search_req->handle->status;
-                       goto done;
-               }
-
-               if (ac->search_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-
-               if (ac->search_res == NULL) {
-                       return LDB_ERR_NO_SUCH_OBJECT;
-               }
-
-               /* self search done, go on */
-               return password_hash_mod_search_dom(handle);
-               
-       case PH_MOD_SEARCH_DOM:
-               ret = ldb_wait(ac->dom_req->handle, LDB_WAIT_NONE);
-
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->dom_req->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->dom_req->handle->status;
-                       goto done;
-               }
-
-               if (ac->dom_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-
-               /* domain search done, go on */
-               return password_hash_mod_do_mod(handle);
-
-       case PH_MOD_DO_MOD:
-               ret = ldb_wait(ac->mod_req->handle, LDB_WAIT_NONE);
-
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->mod_req->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->mod_req->handle->status;
-                       goto done;
-               }
-
-               if (ac->mod_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-
-               break;
-               
-       default:
-               ret = LDB_ERR_OPERATIONS_ERROR;
-               goto done;
-       }
-
-       ret = LDB_SUCCESS;
-
-done:
-       handle->state = LDB_ASYNC_DONE;
-       return ret;
-}
-
-static int ph_wait_all(struct ldb_handle *handle) {
-
-       int ret;
-
-       while (handle->state != LDB_ASYNC_DONE) {
-               ret = ph_wait(handle);
-               if (ret != LDB_SUCCESS) {
-                       return ret;
-               }
-       }
-
-       return handle->status;
-}
-
-static int password_hash_wait(struct ldb_handle *handle, enum ldb_wait_type type)
-{
-       if (type == LDB_WAIT_ALL) {
-               return ph_wait_all(handle);
-       } else {
-               return ph_wait(handle);
-       }
+       return ldb_next_request(ac->module, mod_req);
 }
 
 _PUBLIC_ const struct ldb_module_ops ldb_password_hash_module_ops = {
        .name          = "password_hash",
        .add           = password_hash_add,
-       .modify        = password_hash_modify,
-       .wait          = password_hash_wait
+       .modify        = password_hash_modify
 };