Correct "specifiy" typos.
[samba.git] / source4 / dsdb / samdb / ldb_modules / password_hash.c
index 0f078b5c76fcf28dac12b56f903f1516e4e39adb..b38f1674594e66b24af5ccaf082a653755c9944f 100644 (file)
  */
 
 #include "includes.h"
-#include "libcli/ldap/ldap_ndr.h"
 #include "ldb_module.h"
-#include "librpc/gen_ndr/misc.h"
-#include "librpc/gen_ndr/samr.h"
 #include "libcli/auth/libcli_auth.h"
-#include "libcli/security/security.h"
+#include "libcli/security/dom_sid.h"
 #include "system/kerberos.h"
 #include "auth/kerberos/kerberos.h"
-#include "system/time.h"
 #include "dsdb/samdb/samdb.h"
-#include "../libds/common/flags.h"
+#include "dsdb/samdb/ldb_modules/util.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 "param/param.h"
+#include "lib/krb5_wrap/krb5_samba.h"
+
+#ifdef ENABLE_GPGME
+#undef class
+#include <gpgme.h>
+#endif
 
 /* If we have decided there is a reason to work on this request, then
  * setup all the password hash types correctly.
@@ -94,13 +95,22 @@ struct ph_context {
 
        struct ldb_reply *search_res;
 
+       struct ldb_message *update_msg;
+
        struct dsdb_control_password_change_status *status;
+       struct dsdb_control_password_change *change;
 
-       bool pwd_reset;
+       const char **gpg_key_ids;
 
+       bool pwd_reset;
        bool change_status;
        bool hash_values;
-       bool change_old_pw_checked;
+       bool userPassword;
+       bool update_password;
+       bool update_lastset;
+       bool pwd_last_set_bypass;
+       bool pwd_last_set_default;
+       bool smartcard_reset;
 };
 
 
@@ -116,6 +126,7 @@ struct setup_password_fields_io {
                const char *sAMAccountName;
                const char *user_principal_name;
                bool is_computer;
+               bool is_krbtgt;
                uint32_t restrictions;
        } u;
 
@@ -157,6 +168,421 @@ struct setup_password_fields_io {
        } g;
 };
 
+static int msg_find_old_and_new_pwd_val(const struct ldb_message *msg,
+                                       const char *name,
+                                       enum ldb_request_type operation,
+                                       const struct ldb_val **new_val,
+                                       const struct ldb_val **old_val);
+
+static int password_hash_bypass(struct ldb_module *module, struct ldb_request *request)
+{
+       struct ldb_context *ldb = ldb_module_get_ctx(module);
+       const struct ldb_message *msg;
+       struct ldb_message_element *nte;
+       struct ldb_message_element *lme;
+       struct ldb_message_element *nthe;
+       struct ldb_message_element *lmhe;
+       struct ldb_message_element *sce;
+
+       switch (request->operation) {
+       case LDB_ADD:
+               msg = request->op.add.message;
+               break;
+       case LDB_MODIFY:
+               msg = request->op.mod.message;
+               break;
+       default:
+               return ldb_next_request(module, request);
+       }
+
+       /* nobody must touch password histories and 'supplementalCredentials' */
+       nte = dsdb_get_single_valued_attr(msg, "unicodePwd",
+                                         request->operation);
+       lme = dsdb_get_single_valued_attr(msg, "dBCSPwd",
+                                         request->operation);
+       nthe = dsdb_get_single_valued_attr(msg, "ntPwdHistory",
+                                          request->operation);
+       lmhe = dsdb_get_single_valued_attr(msg, "lmPwdHistory",
+                                          request->operation);
+       sce = dsdb_get_single_valued_attr(msg, "supplementalCredentials",
+                                         request->operation);
+
+#define CHECK_HASH_ELEMENT(e, min, max) do {\
+       if (e && e->num_values) { \
+               unsigned int _count; \
+               if (e->num_values != 1) { \
+                       return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION, \
+                                        "num_values != 1"); \
+               } \
+               if ((e->values[0].length % 16) != 0) { \
+                       return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION, \
+                                        "length % 16 != 0"); \
+               } \
+               _count = e->values[0].length / 16; \
+               if (_count < min) { \
+                       return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION, \
+                                        "count < min"); \
+               } \
+               if (_count > max) { \
+                       return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION, \
+                                        "count > max"); \
+               } \
+       } \
+} while (0)
+
+       CHECK_HASH_ELEMENT(nte, 1, 1);
+       CHECK_HASH_ELEMENT(lme, 1, 1);
+       CHECK_HASH_ELEMENT(nthe, 1, INT32_MAX);
+       CHECK_HASH_ELEMENT(lmhe, 1, INT32_MAX);
+
+       if (sce && sce->num_values) {
+               enum ndr_err_code ndr_err;
+               struct supplementalCredentialsBlob *scb;
+               struct supplementalCredentialsPackage *scpp = NULL;
+               struct supplementalCredentialsPackage *scpk = NULL;
+               struct supplementalCredentialsPackage *scpkn = NULL;
+               struct supplementalCredentialsPackage *scpct = NULL;
+               DATA_BLOB scpbp = data_blob_null;
+               DATA_BLOB scpbk = data_blob_null;
+               DATA_BLOB scpbkn = data_blob_null;
+               DATA_BLOB scpbct = data_blob_null;
+               DATA_BLOB blob;
+               uint32_t i;
+
+               if (sce->num_values != 1) {
+                       return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                        "num_values != 1");
+               }
+
+               scb = talloc_zero(request, struct supplementalCredentialsBlob);
+               if (!scb) {
+                       return ldb_module_oom(module);
+               }
+
+               ndr_err = ndr_pull_struct_blob_all(&sce->values[0], scb, scb,
+                               (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
+               if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
+                       return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                        "ndr_pull_struct_blob_all");
+               }
+
+               if (scb->sub.num_packages < 2) {
+                       return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                        "num_packages < 2");
+               }
+
+               for (i=0; i < scb->sub.num_packages; i++) {
+                       DATA_BLOB subblob;
+
+                       subblob = strhex_to_data_blob(scb, scb->sub.packages[i].data);
+                       if (subblob.data == NULL) {
+                               return ldb_module_oom(module);
+                       }
+
+                       if (strcmp(scb->sub.packages[i].name, "Packages") == 0) {
+                               if (scpp) {
+                                       return ldb_error(ldb,
+                                                        LDB_ERR_CONSTRAINT_VIOLATION,
+                                                        "Packages twice");
+                               }
+                               scpp = &scb->sub.packages[i];
+                               scpbp = subblob;
+                               continue;
+                       }
+                       if (strcmp(scb->sub.packages[i].name, "Primary:Kerberos") == 0) {
+                               if (scpk) {
+                                       return ldb_error(ldb,
+                                                        LDB_ERR_CONSTRAINT_VIOLATION,
+                                                        "Primary:Kerberos twice");
+                               }
+                               scpk = &scb->sub.packages[i];
+                               scpbk = subblob;
+                               continue;
+                       }
+                       if (strcmp(scb->sub.packages[i].name, "Primary:Kerberos-Newer-Keys") == 0) {
+                               if (scpkn) {
+                                       return ldb_error(ldb,
+                                                        LDB_ERR_CONSTRAINT_VIOLATION,
+                                                        "Primary:Kerberos-Newer-Keys twice");
+                               }
+                               scpkn = &scb->sub.packages[i];
+                               scpbkn = subblob;
+                               continue;
+                       }
+                       if (strcmp(scb->sub.packages[i].name, "Primary:CLEARTEXT") == 0) {
+                               if (scpct) {
+                                       return ldb_error(ldb,
+                                                        LDB_ERR_CONSTRAINT_VIOLATION,
+                                                        "Primary:CLEARTEXT twice");
+                               }
+                               scpct = &scb->sub.packages[i];
+                               scpbct = subblob;
+                               continue;
+                       }
+
+                       data_blob_free(&subblob);
+               }
+
+               if (scpp == NULL) {
+                       return ldb_error(ldb,
+                                        LDB_ERR_CONSTRAINT_VIOLATION,
+                                        "Primary:Packages missing");
+               }
+
+               if (scpk == NULL) {
+                       /*
+                        * If Primary:Kerberos is missing w2k8r2 reboots
+                        * when a password is changed.
+                        */
+                       return ldb_error(ldb,
+                                        LDB_ERR_CONSTRAINT_VIOLATION,
+                                        "Primary:Kerberos missing");
+               }
+
+               if (scpp) {
+                       struct package_PackagesBlob *p;
+                       uint32_t n;
+
+                       p = talloc_zero(scb, struct package_PackagesBlob);
+                       if (p == NULL) {
+                               return ldb_module_oom(module);
+                       }
+
+                       ndr_err = ndr_pull_struct_blob(&scpbp, p, p,
+                                       (ndr_pull_flags_fn_t)ndr_pull_package_PackagesBlob);
+                       if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "ndr_pull_struct_blob Packages");
+                       }
+
+                       if (p->names == NULL) {
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "Packages names == NULL");
+                       }
+
+                       for (n = 0; p->names[n]; n++) {
+                               /* noop */
+                       }
+
+                       if (scb->sub.num_packages != (n + 1)) {
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "Packages num_packages != num_names + 1");
+                       }
+
+                       talloc_free(p);
+               }
+
+               if (scpk) {
+                       struct package_PrimaryKerberosBlob *k;
+
+                       k = talloc_zero(scb, struct package_PrimaryKerberosBlob);
+                       if (k == NULL) {
+                               return ldb_module_oom(module);
+                       }
+
+                       ndr_err = ndr_pull_struct_blob(&scpbk, k, k,
+                                       (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
+                       if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "ndr_pull_struct_blob PrimaryKerberos");
+                       }
+
+                       if (k->version != 3) {
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "PrimaryKerberos version != 3");
+                       }
+
+                       if (k->ctr.ctr3.salt.string == NULL) {
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "PrimaryKerberos salt == NULL");
+                       }
+
+                       if (strlen(k->ctr.ctr3.salt.string) == 0) {
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "PrimaryKerberos strlen(salt) == 0");
+                       }
+
+                       if (k->ctr.ctr3.num_keys != 2) {
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "PrimaryKerberos num_keys != 2");
+                       }
+
+                       if (k->ctr.ctr3.num_old_keys > k->ctr.ctr3.num_keys) {
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "PrimaryKerberos num_old_keys > num_keys");
+                       }
+
+                       if (k->ctr.ctr3.keys[0].keytype != ENCTYPE_DES_CBC_MD5) {
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "PrimaryKerberos key[0] != DES_CBC_MD5");
+                       }
+                       if (k->ctr.ctr3.keys[1].keytype != ENCTYPE_DES_CBC_CRC) {
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "PrimaryKerberos key[1] != DES_CBC_CRC");
+                       }
+
+                       if (k->ctr.ctr3.keys[0].value_len != 8) {
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "PrimaryKerberos key[0] value_len != 8");
+                       }
+                       if (k->ctr.ctr3.keys[1].value_len != 8) {
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "PrimaryKerberos key[1] value_len != 8");
+                       }
+
+                       for (i = 0; i < k->ctr.ctr3.num_old_keys; i++) {
+                               if (k->ctr.ctr3.old_keys[i].keytype ==
+                                   k->ctr.ctr3.keys[i].keytype &&
+                                   k->ctr.ctr3.old_keys[i].value_len ==
+                                   k->ctr.ctr3.keys[i].value_len) {
+                                       continue;
+                               }
+
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "PrimaryKerberos old_keys type/value_len doesn't match");
+                       }
+
+                       talloc_free(k);
+               }
+
+               if (scpkn) {
+                       struct package_PrimaryKerberosBlob *k;
+
+                       k = talloc_zero(scb, struct package_PrimaryKerberosBlob);
+                       if (k == NULL) {
+                               return ldb_module_oom(module);
+                       }
+
+                       ndr_err = ndr_pull_struct_blob(&scpbkn, k, k,
+                                       (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
+                       if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "ndr_pull_struct_blob PrimaryKerberosNeverKeys");
+                       }
+
+                       if (k->version != 4) {
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "KerberosNerverKeys version != 4");
+                       }
+
+                       if (k->ctr.ctr4.salt.string == NULL) {
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "KerberosNewerKeys salt == NULL");
+                       }
+
+                       if (strlen(k->ctr.ctr4.salt.string) == 0) {
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "KerberosNewerKeys strlen(salt) == 0");
+                       }
+
+                       if (k->ctr.ctr4.num_keys != 4) {
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "KerberosNewerKeys num_keys != 2");
+                       }
+
+                       if (k->ctr.ctr4.num_old_keys > k->ctr.ctr4.num_keys) {
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "KerberosNewerKeys num_old_keys > num_keys");
+                       }
+
+                       if (k->ctr.ctr4.num_older_keys > k->ctr.ctr4.num_old_keys) {
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "KerberosNewerKeys num_older_keys > num_old_keys");
+                       }
+
+                       if (k->ctr.ctr4.keys[0].keytype != ENCTYPE_AES256_CTS_HMAC_SHA1_96) {
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "KerberosNewerKeys key[0] != AES256");
+                       }
+                       if (k->ctr.ctr4.keys[1].keytype != ENCTYPE_AES128_CTS_HMAC_SHA1_96) {
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "KerberosNewerKeys key[1] != AES128");
+                       }
+                       if (k->ctr.ctr4.keys[2].keytype != ENCTYPE_DES_CBC_MD5) {
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "KerberosNewerKeys key[2] != DES_CBC_MD5");
+                       }
+                       if (k->ctr.ctr4.keys[3].keytype != ENCTYPE_DES_CBC_CRC) {
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "KerberosNewerKeys key[3] != DES_CBC_CRC");
+                       }
+
+                       if (k->ctr.ctr4.keys[0].value_len != 32) {
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "KerberosNewerKeys key[0] value_len != 32");
+                       }
+                       if (k->ctr.ctr4.keys[1].value_len != 16) {
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "KerberosNewerKeys key[1] value_len != 16");
+                       }
+                       if (k->ctr.ctr4.keys[2].value_len != 8) {
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "KerberosNewerKeys key[2] value_len != 8");
+                       }
+                       if (k->ctr.ctr4.keys[3].value_len != 8) {
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "KerberosNewerKeys key[3] value_len != 8");
+                       }
+
+                       /*
+                        * TODO:
+                        * Maybe we can check old and older keys here.
+                        * But we need to do some tests, if the old keys
+                        * can be taken from the PrimaryKerberos blob
+                        * (with only des keys), when the domain was upgraded
+                        * from w2k3 to w2k8.
+                        */
+
+                       talloc_free(k);
+               }
+
+               if (scpct) {
+                       struct package_PrimaryCLEARTEXTBlob *ct;
+
+                       ct = talloc_zero(scb, struct package_PrimaryCLEARTEXTBlob);
+                       if (ct == NULL) {
+                               return ldb_module_oom(module);
+                       }
+
+                       ndr_err = ndr_pull_struct_blob(&scpbct, ct, ct,
+                                       (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryCLEARTEXTBlob);
+                       if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "ndr_pull_struct_blob PrimaryCLEARTEXT");
+                       }
+
+                       if ((ct->cleartext.length % 2) != 0) {
+                               return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                                "PrimaryCLEARTEXT length % 2 != 0");
+                       }
+
+                       talloc_free(ct);
+               }
+
+               ndr_err = ndr_push_struct_blob(&blob, scb, scb,
+                               (ndr_push_flags_fn_t)ndr_push_supplementalCredentialsBlob);
+               if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
+                       return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                        "ndr_pull_struct_blob_all");
+               }
+
+               if (sce->values[0].length != blob.length) {
+                       return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                        "supplementalCredentialsBlob length differ");
+               }
+
+               if (memcmp(sce->values[0].data, blob.data, blob.length) != 0) {
+                       return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
+                                        "supplementalCredentialsBlob memcmp differ");
+               }
+
+               talloc_free(scb);
+       }
+
+       ldb_debug(ldb, LDB_DEBUG_TRACE, "password_hash_bypass - validated\n");
+       return ldb_next_request(module, request);
+}
+
 /* Get the NT hash, and fill it in as an entry in the password history, 
    and specify it into io->g.nt_hash */
 
@@ -241,18 +667,18 @@ 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_principal salt_principal;
+       krb5_data salt;
        krb5_keyblock key;
        krb5_data cleartext_data;
 
        ldb = ldb_module_get_ctx(io->ac->module);
-       cleartext_data.data = io->n.cleartext_utf8->data;
+       cleartext_data.data = (char *)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
-        * samba-technical@samba.org */
+        * samba-technical@lists.samba.org */
 
        /*
         * Determine a salting principal
@@ -276,7 +702,7 @@ static int setup_kerberos_keys(struct setup_password_fields_io *io)
                        return ldb_oom(ldb);
                }
                
-               krb5_ret = krb5_make_principal(io->smb_krb5_context->krb5_context,
+               krb5_ret = smb_krb5_make_principal(io->smb_krb5_context->krb5_context,
                                               &salt_principal,
                                               io->ac->status->domain_data.realm,
                                               "host", saltbody, NULL);
@@ -294,12 +720,12 @@ static int setup_kerberos_keys(struct setup_password_fields_io *io)
                        p[0] = '\0';
                }
 
-               krb5_ret = krb5_make_principal(io->smb_krb5_context->krb5_context,
+               krb5_ret = smb_krb5_make_principal(io->smb_krb5_context->krb5_context,
                                               &salt_principal,
                                               io->ac->status->domain_data.realm,
                                               user_principal_name, NULL);
        } else {
-               krb5_ret = krb5_make_principal(io->smb_krb5_context->krb5_context,
+               krb5_ret = smb_krb5_make_principal(io->smb_krb5_context->krb5_context,
                                               &salt_principal,
                                               io->ac->status->domain_data.realm,
                                               io->u.sAMAccountName, NULL);
@@ -316,7 +742,7 @@ static int setup_kerberos_keys(struct setup_password_fields_io *io)
        /*
         * create salt from salt_principal
         */
-       krb5_ret = krb5_get_pw_salt(io->smb_krb5_context->krb5_context,
+       krb5_ret = smb_krb5_get_pw_salt(io->smb_krb5_context->krb5_context,
                                    salt_principal, &salt);
        krb5_free_principal(io->smb_krb5_context->krb5_context, salt_principal);
        if (krb5_ret) {
@@ -329,24 +755,26 @@ static int setup_kerberos_keys(struct setup_password_fields_io *io)
        }
        /* create a talloc copy */
        io->g.salt = talloc_strndup(io->ac,
-                                   (char *)salt.saltvalue.data,
-                                   salt.saltvalue.length);
-       krb5_free_salt(io->smb_krb5_context->krb5_context, salt);
+                                   (char *)salt.data,
+                                   salt.length);
+       smb_krb5_free_data_contents(io->smb_krb5_context->krb5_context, &salt);
        if (!io->g.salt) {
                return ldb_oom(ldb);
        }
-       salt.saltvalue.data     = discard_const(io->g.salt);
-       salt.saltvalue.length   = strlen(io->g.salt);
+       /* now use the talloced copy of the salt */
+       salt.data       = discard_const(io->g.salt);
+       salt.length     = strlen(io->g.salt);
 
        /*
         * create ENCTYPE_AES256_CTS_HMAC_SHA1_96 key out of
         * the salt and the cleartext password
         */
-       krb5_ret = krb5_string_to_key_data_salt(io->smb_krb5_context->krb5_context,
-                                               ENCTYPE_AES256_CTS_HMAC_SHA1_96,
-                                               cleartext_data,
-                                               salt,
-                                               &key);
+       krb5_ret = smb_krb5_create_key_from_string(io->smb_krb5_context->krb5_context,
+                                                  NULL,
+                                                  &salt,
+                                                  &cleartext_data,
+                                                  ENCTYPE_AES256_CTS_HMAC_SHA1_96,
+                                                  &key);
        if (krb5_ret) {
                ldb_asprintf_errstring(ldb,
                                       "setup_kerberos_keys: "
@@ -356,8 +784,8 @@ static int setup_kerberos_keys(struct setup_password_fields_io *io)
                return LDB_ERR_OPERATIONS_ERROR;
        }
        io->g.aes_256 = data_blob_talloc(io->ac,
-                                        key.keyvalue.data,
-                                        key.keyvalue.length);
+                                        KRB5_KEY_DATA(&key),
+                                        KRB5_KEY_LENGTH(&key));
        krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
        if (!io->g.aes_256.data) {
                return ldb_oom(ldb);
@@ -367,11 +795,12 @@ static int setup_kerberos_keys(struct setup_password_fields_io *io)
         * create ENCTYPE_AES128_CTS_HMAC_SHA1_96 key out of
         * the salt and the cleartext password
         */
-       krb5_ret = krb5_string_to_key_data_salt(io->smb_krb5_context->krb5_context,
-                                               ENCTYPE_AES128_CTS_HMAC_SHA1_96,
-                                               cleartext_data,
-                                               salt,
-                                               &key);
+       krb5_ret = smb_krb5_create_key_from_string(io->smb_krb5_context->krb5_context,
+                                                  NULL,
+                                                  &salt,
+                                                  &cleartext_data,
+                                                  ENCTYPE_AES128_CTS_HMAC_SHA1_96,
+                                                  &key);
        if (krb5_ret) {
                ldb_asprintf_errstring(ldb,
                                       "setup_kerberos_keys: "
@@ -381,8 +810,8 @@ static int setup_kerberos_keys(struct setup_password_fields_io *io)
                return LDB_ERR_OPERATIONS_ERROR;
        }
        io->g.aes_128 = data_blob_talloc(io->ac,
-                                        key.keyvalue.data,
-                                        key.keyvalue.length);
+                                        KRB5_KEY_DATA(&key),
+                                        KRB5_KEY_LENGTH(&key));
        krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
        if (!io->g.aes_128.data) {
                return ldb_oom(ldb);
@@ -392,11 +821,12 @@ static int setup_kerberos_keys(struct setup_password_fields_io *io)
         * create ENCTYPE_DES_CBC_MD5 key out of
         * the salt and the cleartext password
         */
-       krb5_ret = krb5_string_to_key_data_salt(io->smb_krb5_context->krb5_context,
-                                               ENCTYPE_DES_CBC_MD5,
-                                               cleartext_data,
-                                               salt,
-                                               &key);
+       krb5_ret = smb_krb5_create_key_from_string(io->smb_krb5_context->krb5_context,
+                                                  NULL,
+                                                  &salt,
+                                                  &cleartext_data,
+                                                  ENCTYPE_DES_CBC_MD5,
+                                                  &key);
        if (krb5_ret) {
                ldb_asprintf_errstring(ldb,
                                       "setup_kerberos_keys: "
@@ -406,8 +836,8 @@ static int setup_kerberos_keys(struct setup_password_fields_io *io)
                return LDB_ERR_OPERATIONS_ERROR;
        }
        io->g.des_md5 = data_blob_talloc(io->ac,
-                                        key.keyvalue.data,
-                                        key.keyvalue.length);
+                                        KRB5_KEY_DATA(&key),
+                                        KRB5_KEY_LENGTH(&key));
        krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
        if (!io->g.des_md5.data) {
                return ldb_oom(ldb);
@@ -417,11 +847,12 @@ static int setup_kerberos_keys(struct setup_password_fields_io *io)
         * create ENCTYPE_DES_CBC_CRC key out of
         * the salt and the cleartext password
         */
-       krb5_ret = krb5_string_to_key_data_salt(io->smb_krb5_context->krb5_context,
-                                               ENCTYPE_DES_CBC_CRC,
-                                               cleartext_data,
-                                               salt,
-                                               &key);
+       krb5_ret = smb_krb5_create_key_from_string(io->smb_krb5_context->krb5_context,
+                                                  NULL,
+                                                  &salt,
+                                                  &cleartext_data,
+                                                  ENCTYPE_DES_CBC_CRC,
+                                                  &key);
        if (krb5_ret) {
                ldb_asprintf_errstring(ldb,
                                       "setup_kerberos_keys: "
@@ -431,8 +862,8 @@ static int setup_kerberos_keys(struct setup_password_fields_io *io)
                return LDB_ERR_OPERATIONS_ERROR;
        }
        io->g.des_crc = data_blob_talloc(io->ac,
-                                        key.keyvalue.data,
-                                        key.keyvalue.length);
+                                        KRB5_KEY_DATA(&key),
+                                        KRB5_KEY_LENGTH(&key));
        krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
        if (!io->g.des_crc.data) {
                return ldb_oom(ldb);
@@ -964,7 +1395,7 @@ static int setup_primary_wdigest(struct setup_password_fields_io *io,
        }
 
        for (i=0; i < ARRAY_SIZE(wdigest); i++) {
-               struct MD5Context md5;
+               MD5_CTX md5;
                MD5Init(&md5);
                if (wdigest[i].nt4dom) {
                        MD5Update(&md5, wdigest[i].nt4dom->data, wdigest[i].nt4dom->length);
@@ -983,17 +1414,152 @@ static int setup_primary_wdigest(struct setup_password_fields_io *io,
        return LDB_SUCCESS;
 }
 
+static int setup_primary_samba_gpg(struct setup_password_fields_io *io,
+                                  struct package_PrimarySambaGPGBlob *pgb)
+{
+       struct ldb_context *ldb = ldb_module_get_ctx(io->ac->module);
+#ifdef ENABLE_GPGME
+       gpgme_error_t gret;
+       gpgme_ctx_t ctx = NULL;
+       size_t num_keys = str_list_length(io->ac->gpg_key_ids);
+       gpgme_key_t keys[num_keys+1];
+       size_t ki = 0;
+       size_t kr = 0;
+       gpgme_data_t plain_data = NULL;
+       gpgme_data_t crypt_data = NULL;
+       size_t crypt_length = 0;
+       char *crypt_mem = NULL;
+
+       gret = gpgme_new(&ctx);
+       if (gret != GPG_ERR_NO_ERROR) {
+               ldb_debug(ldb, LDB_DEBUG_ERROR,
+                         "%s:%s: gret[%u] %s\n",
+                         __location__, __func__,
+                         gret, gpgme_strerror(gret));
+               return ldb_module_operr(io->ac->module);
+       }
+
+       gpgme_set_armor(ctx, 1);
+
+       gret = gpgme_data_new_from_mem(&plain_data,
+                                      (const char *)io->n.cleartext_utf16->data,
+                                      io->n.cleartext_utf16->length,
+                                      0 /* no copy */);
+       if (gret != GPG_ERR_NO_ERROR) {
+               ldb_debug(ldb, LDB_DEBUG_ERROR,
+                         "%s:%s: gret[%u] %s\n",
+                         __location__, __func__,
+                         gret, gpgme_strerror(gret));
+               gpgme_release(ctx);
+               return ldb_module_operr(io->ac->module);
+       }
+       gret = gpgme_data_new(&crypt_data);
+       if (gret != GPG_ERR_NO_ERROR) {
+               ldb_debug(ldb, LDB_DEBUG_ERROR,
+                         "%s:%s: gret[%u] %s\n",
+                         __location__, __func__,
+                         gret, gpgme_strerror(gret));
+               gpgme_data_release(plain_data);
+               gpgme_release(ctx);
+               return ldb_module_operr(io->ac->module);
+       }
+
+       for (ki = 0; ki < num_keys; ki++) {
+               const char *key_id = io->ac->gpg_key_ids[ki];
+               size_t len = strlen(key_id);
+
+               keys[ki] = NULL;
+
+               if (len < 16) {
+                       ldb_debug(ldb, LDB_DEBUG_FATAL,
+                                 "%s:%s: ki[%zu] key_id[%s] strlen < 16, "
+                                 "please specify at least the 64bit key id\n",
+                                 __location__, __func__,
+                                 ki, key_id);
+                       for (kr = 0; keys[kr] != NULL; kr++) {
+                               gpgme_key_release(keys[kr]);
+                       }
+                       gpgme_data_release(crypt_data);
+                       gpgme_data_release(plain_data);
+                       gpgme_release(ctx);
+                       return ldb_module_operr(io->ac->module);
+               }
+
+               gret = gpgme_get_key(ctx, key_id, &keys[ki], 0 /* public key */);
+               if (gret != GPG_ERR_NO_ERROR) {
+                       keys[ki] = NULL;
+                       ldb_debug(ldb, LDB_DEBUG_ERROR,
+                                 "%s:%s: ki[%zu] key_id[%s] gret[%u] %s\n",
+                                 __location__, __func__,
+                                 ki, key_id,
+                                 gret, gpgme_strerror(gret));
+                       for (kr = 0; keys[kr] != NULL; kr++) {
+                               gpgme_key_release(keys[kr]);
+                       }
+                       gpgme_data_release(crypt_data);
+                       gpgme_data_release(plain_data);
+                       gpgme_release(ctx);
+                       return ldb_module_operr(io->ac->module);
+               }
+       }
+       keys[ki] = NULL;
+
+       gret = gpgme_op_encrypt(ctx, keys,
+                               GPGME_ENCRYPT_ALWAYS_TRUST,
+                               plain_data, crypt_data);
+       gpgme_data_release(plain_data);
+       plain_data = NULL;
+       for (kr = 0; keys[kr] != NULL; kr++) {
+               gpgme_key_release(keys[kr]);
+               keys[kr] = NULL;
+       }
+       gpgme_release(ctx);
+       ctx = NULL;
+       if (gret != GPG_ERR_NO_ERROR) {
+               ldb_debug(ldb, LDB_DEBUG_ERROR,
+                         "%s:%s: gret[%u] %s\n",
+                         __location__, __func__,
+                         gret, gpgme_strerror(gret));
+               gpgme_data_release(crypt_data);
+               return ldb_module_operr(io->ac->module);
+       }
+
+       crypt_mem = gpgme_data_release_and_get_mem(crypt_data, &crypt_length);
+       crypt_data = NULL;
+       if (crypt_mem == NULL) {
+               return ldb_module_oom(io->ac->module);
+       }
+
+       pgb->gpg_blob = data_blob_talloc(io->ac,
+                                        (const uint8_t *)crypt_mem,
+                                        crypt_length);
+       gpgme_free(crypt_mem);
+       crypt_mem = NULL;
+       crypt_length = 0;
+       if (pgb->gpg_blob.data == NULL) {
+               return ldb_module_oom(io->ac->module);
+       }
+
+       return LDB_SUCCESS;
+#else /* ENABLE_GPGME */
+       ldb_debug_set(ldb, LDB_DEBUG_FATAL,
+                     "You configured 'password hash gpg key ids', "
+                     "but GPGME support is missing. (%s:%d)",
+                     __FILE__, __LINE__);
+       return LDB_ERR_UNWILLING_TO_PERFORM;
+#endif /* else ENABLE_GPGME */
+}
+
 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-Newer-Keys, Kerberos, WDigest and CLEARTEXT) */
+       /* Packages + (Kerberos-Newer-Keys, Kerberos, WDigest, CLEARTEXT, SambaGPG) */
        uint32_t num_names = 0;
-       const char *names[1+4];
+       const char *names[1+5];
        uint32_t num_packages = 0;
-       struct supplementalCredentialsPackage packages[1+4];
+       struct supplementalCredentialsPackage packages[1+5];
        /* Packages */
        struct supplementalCredentialsPackage *pp = NULL;
        struct package_PackagesBlob pb;
@@ -1023,14 +1589,22 @@ static int setup_supplemental_field(struct setup_password_fields_io *io)
        struct package_PrimaryCLEARTEXTBlob pcb;
        DATA_BLOB pcb_blob;
        char *pcb_hexstr;
+       /* Primary:SambaGPG */
+       const char **ng = NULL;
+       struct supplementalCredentialsPackage *pg = NULL;
+       struct package_PrimarySambaGPGBlob pgb;
+       DATA_BLOB pgb_blob;
+       char *pgb_hexstr;
        int ret;
        enum ndr_err_code ndr_err;
        uint8_t zero16[16];
        bool do_newer_keys = false;
        bool do_cleartext = false;
+       bool do_samba_gpg = false;
 
        ZERO_STRUCT(zero16);
        ZERO_STRUCT(names);
+       ZERO_STRUCT(packages);
 
        ldb = ldb_module_get_ctx(io->ac->module);
 
@@ -1042,27 +1616,17 @@ static int setup_supplemental_field(struct setup_password_fields_io *io)
                return LDB_SUCCESS;
        }
 
-       /* if there's an old supplementaCredentials blob then parse it */
+       /* if there's an old supplementaCredentials blob then use it */
        if (io->o.supplemental) {
-               ndr_err = ndr_pull_struct_blob_all(io->o.supplemental, io->ac,
-                                                  &_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(ldb,
-                                              "setup_supplemental_field: "
-                                              "failed to pull old supplementalCredentialsBlob: %s",
-                                              nt_errstr(status));
-                       return LDB_ERR_OPERATIONS_ERROR;
-               }
-
-               if (_old_scb.sub.signature == SUPPLEMENTAL_CREDENTIALS_SIGNATURE) {
-                       old_scb = &_old_scb;
+               if (io->o.scb.sub.signature == SUPPLEMENTAL_CREDENTIALS_SIGNATURE) {
+                       old_scb = &io->o.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);
+                                 "setup_supplemental_field: "
+                                 "supplementalCredentialsBlob "
+                                 "signature[0x%04X] expected[0x%04X]",
+                                 io->o.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 */
@@ -1073,6 +1637,10 @@ static int setup_supplemental_field(struct setup_password_fields_io *io)
                do_cleartext = true;
        }
 
+       if (io->ac->gpg_key_ids != NULL) {
+               do_samba_gpg = true;
+       }
+
        /*
         * The ordering is this
         *
@@ -1080,9 +1648,16 @@ static int setup_supplemental_field(struct setup_password_fields_io *io)
         * Primary:Kerberos
         * Primary:WDigest
         * Primary:CLEARTEXT (optional)
+        * Primary:SambaGPG (optional)
         *
         * And the 'Packages' package is insert before the last
         * other package.
+        *
+        * Note: it's important that Primary:SambaGPG is added as
+        * the last element. This is the indication that it matches
+        * the current password. When a password change happens on
+        * a Windows DC, it will keep the old Primary:SambaGPG value,
+        * but as the first element.
         */
        if (do_newer_keys) {
                /* Primary:Kerberos-Newer-Keys */
@@ -1094,7 +1669,7 @@ static int setup_supplemental_field(struct setup_password_fields_io *io)
        nk = &names[num_names++];
        pk = &packages[num_packages++];
 
-       if (!do_cleartext) {
+       if (!do_cleartext && !do_samba_gpg) {
                /* Packages */
                pp = &packages[num_packages++];
        }
@@ -1104,14 +1679,25 @@ static int setup_supplemental_field(struct setup_password_fields_io *io)
        pd = &packages[num_packages++];
 
        if (do_cleartext) {
-               /* Packages */
-               pp = &packages[num_packages++];
+               if (!do_samba_gpg) {
+                       /* Packages */
+                       pp = &packages[num_packages++];
+               }
 
                /* Primary:CLEARTEXT */
                nc = &names[num_names++];
                pc = &packages[num_packages++];
        }
 
+       if (do_samba_gpg) {
+               /* Packages */
+               pp = &packages[num_packages++];
+
+               /* Primary:SambaGPG */
+               ng = &names[num_names++];
+               pg = &packages[num_packages++];
+       }
+
        if (pkn) {
                /*
                 * setup 'Primary:Kerberos-Newer-Keys' element
@@ -1229,6 +1815,36 @@ static int setup_supplemental_field(struct setup_password_fields_io *io)
                pc->data        = pcb_hexstr;
        }
 
+       /*
+        * setup 'Primary:SambaGPG' element
+        */
+       if (pg) {
+               *ng             = "SambaGPG";
+
+               ret = setup_primary_samba_gpg(io, &pgb);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
+               }
+
+               ndr_err = ndr_push_struct_blob(&pgb_blob, io->ac, &pgb,
+                       (ndr_push_flags_fn_t)ndr_push_package_PrimarySambaGPGBlob);
+               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_PrimarySambaGPGBlob: %s",
+                                       nt_errstr(status));
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+               pgb_hexstr = data_blob_hex_string_upper(io->ac, &pgb_blob);
+               if (!pgb_hexstr) {
+                       return ldb_oom(ldb);
+               }
+               pg->name        = "Primary:SambaGPG";
+               pg->reserved    = 1;
+               pg->data        = pgb_hexstr;
+       }
+
        /*
         * setup 'Packages' element
         */
@@ -1256,6 +1872,7 @@ static int setup_supplemental_field(struct setup_password_fields_io *io)
         * setup 'supplementalCredentials' value
         */
        ZERO_STRUCT(scb);
+       scb.sub.signature       = SUPPLEMENTAL_CREDENTIALS_SIGNATURE;
        scb.sub.num_packages    = num_packages;
        scb.sub.packages        = packages;
 
@@ -1276,8 +1893,163 @@ static int setup_supplemental_field(struct setup_password_fields_io *io)
 
 static int setup_last_set_field(struct setup_password_fields_io *io)
 {
-       /* set it as now */
-       unix_to_nt_time(&io->g.last_set, time(NULL));
+       struct ldb_context *ldb = ldb_module_get_ctx(io->ac->module);
+       const struct ldb_message *msg = NULL;
+       struct timeval tv = { .tv_sec = 0 };
+       const struct ldb_val *old_val = NULL;
+       const struct ldb_val *new_val = NULL;
+       int ret;
+
+       switch (io->ac->req->operation) {
+       case LDB_ADD:
+               msg = io->ac->req->op.add.message;
+               break;
+       case LDB_MODIFY:
+               msg = io->ac->req->op.mod.message;
+               break;
+       default:
+               return LDB_ERR_OPERATIONS_ERROR;
+               break;
+       }
+
+       if (io->ac->pwd_last_set_bypass) {
+               struct ldb_message_element *el1 = NULL;
+               struct ldb_message_element *el2 = NULL;
+
+               if (msg == NULL) {
+                       return LDB_ERR_CONSTRAINT_VIOLATION;
+               }
+
+               el1 = dsdb_get_single_valued_attr(msg, "pwdLastSet",
+                                                 io->ac->req->operation);
+               if (el1 == NULL) {
+                       return LDB_ERR_CONSTRAINT_VIOLATION;
+               }
+               el2 = ldb_msg_find_element(msg, "pwdLastSet");
+               if (el2 == NULL) {
+                       return LDB_ERR_CONSTRAINT_VIOLATION;
+               }
+               if (el1 != el2) {
+                       return LDB_ERR_CONSTRAINT_VIOLATION;
+               }
+
+               io->g.last_set = samdb_result_nttime(msg, "pwdLastSet", 0);
+               return LDB_SUCCESS;
+       }
+
+       ret = msg_find_old_and_new_pwd_val(msg, "pwdLastSet",
+                                          io->ac->req->operation,
+                                          &new_val, &old_val);
+       if (ret != LDB_SUCCESS) {
+               return ret;
+       }
+
+       if (old_val != NULL && new_val == NULL) {
+               ldb_set_errstring(ldb,
+                                 "'pwdLastSet' deletion is not allowed!");
+               return LDB_ERR_UNWILLING_TO_PERFORM;
+       }
+
+       io->g.last_set = UINT64_MAX;
+       if (new_val != NULL) {
+               struct ldb_message *tmp_msg = NULL;
+
+               tmp_msg = ldb_msg_new(io->ac);
+               if (tmp_msg == NULL) {
+                       return ldb_module_oom(io->ac->module);
+               }
+
+               if (old_val != NULL) {
+                       NTTIME old_last_set = 0;
+
+                       ret = ldb_msg_add_value(tmp_msg, "oldval",
+                                               old_val, NULL);
+                       if (ret != LDB_SUCCESS) {
+                               return ret;
+                       }
+
+                       old_last_set = samdb_result_nttime(tmp_msg,
+                                                          "oldval",
+                                                          1);
+                       if (io->u.pwdLastSet != old_last_set) {
+                               return dsdb_module_werror(io->ac->module,
+                                       LDB_ERR_NO_SUCH_ATTRIBUTE,
+                                       WERR_DS_CANT_REM_MISSING_ATT_VAL,
+                                       "setup_last_set_field: old pwdLastSet "
+                                       "value not found!");
+                       }
+               }
+
+               ret = ldb_msg_add_value(tmp_msg, "newval",
+                                       new_val, NULL);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
+               }
+
+               io->g.last_set = samdb_result_nttime(tmp_msg,
+                                                    "newval",
+                                                    1);
+       } else if (ldb_msg_find_element(msg, "pwdLastSet")) {
+               ldb_set_errstring(ldb,
+                                 "'pwdLastSet' deletion is not allowed!");
+               return LDB_ERR_UNWILLING_TO_PERFORM;
+       } else if (io->ac->smartcard_reset) {
+               /*
+                * adding UF_SMARTCARD_REQUIRED doesn't update
+                * pwdLastSet implicitly.
+                */
+               io->ac->update_lastset = false;
+       }
+
+       /* only 0 or -1 (0xFFFFFFFFFFFFFFFF) are allowed */
+       switch (io->g.last_set) {
+       case 0:
+               if (!io->ac->pwd_last_set_default) {
+                       break;
+               }
+               if (!io->ac->update_password) {
+                       break;
+               }
+               /* fall through */
+       case UINT64_MAX:
+               if (!io->ac->update_password &&
+                   io->u.pwdLastSet != 0 &&
+                   io->u.pwdLastSet != UINT64_MAX)
+               {
+                       /*
+                        * Just setting pwdLastSet to -1, while not changing
+                        * any password field has no effect if pwdLastSet
+                        * is already non-zero.
+                        */
+                       io->ac->update_lastset = false;
+                       break;
+               }
+               /* -1 means set it as now */
+               GetTimeOfDay(&tv);
+               io->g.last_set = timeval_to_nttime(&tv);
+               break;
+       default:
+               return dsdb_module_werror(io->ac->module,
+                                         LDB_ERR_OTHER,
+                                         WERR_INVALID_PARAMETER,
+                                         "setup_last_set_field: "
+                                         "pwdLastSet must be 0 or -1 only!");
+       }
+
+       if (io->ac->req->operation == LDB_ADD) {
+               /*
+                * We always need to store the value on add
+                * operations.
+                */
+               return LDB_SUCCESS;
+       }
+
+       if (io->g.last_set == io->u.pwdLastSet) {
+               /*
+                * Just setting pwdLastSet to 0, is no-op if it's already 0.
+                */
+               io->ac->update_lastset = false;
+       }
 
        return LDB_SUCCESS;
 }
@@ -1291,50 +2063,61 @@ static int setup_given_passwords(struct setup_password_fields_io *io,
        ldb = ldb_module_get_ctx(io->ac->module);
 
        if (g->cleartext_utf8) {
-               char **cleartext_utf16_str;
                struct ldb_val *cleartext_utf16_blob;
-               size_t converted_pw_len;
 
                cleartext_utf16_blob = talloc(io->ac, struct ldb_val);
                if (!cleartext_utf16_blob) {
                        return ldb_oom(ldb);
                }
                if (!convert_string_talloc(io->ac,
-                                                      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;
+                                          CH_UTF8, CH_UTF16,
+                                          g->cleartext_utf8->data,
+                                          g->cleartext_utf8->length,
+                                          (void *)&cleartext_utf16_blob->data,
+                                          &cleartext_utf16_blob->length)) {
+                       if (g->cleartext_utf8->length != 0) {
+                               talloc_free(cleartext_utf16_blob);
+                               ldb_asprintf_errstring(ldb,
+                                                      "setup_password_fields: "
+                                                      "failed to generate UTF16 password from cleartext UTF8 one for user '%s'!",
+                                                      io->u.sAMAccountName);
+                               return LDB_ERR_CONSTRAINT_VIOLATION;
+                       } else {
+                               /* passwords with length "0" are valid! */
+                               cleartext_utf16_blob->data = NULL;
+                               cleartext_utf16_blob->length = 0;
+                       }
                }
-               *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) {
                        return ldb_oom(ldb);
                }
                if (!convert_string_talloc(io->ac,
-                                                      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;
+                                          CH_UTF16MUNGED, CH_UTF8,
+                                          g->cleartext_utf16->data,
+                                          g->cleartext_utf16->length,
+                                          (void *)&cleartext_utf8_blob->data,
+                                          &cleartext_utf8_blob->length)) {
+                       if (g->cleartext_utf16->length != 0) {
+                               /* We must bail out here, the input wasn't even
+                                * a multiple of 2 bytes */
+                               talloc_free(cleartext_utf8_blob);
+                               ldb_asprintf_errstring(ldb,
+                                                      "setup_password_fields: "
+                                                      "failed to generate UTF8 password from cleartext UTF 16 one for user '%s' - the latter had odd length (length must be a multiple of 2)!",
+                                                      io->u.sAMAccountName);
+                               return LDB_ERR_CONSTRAINT_VIOLATION;
+                       } else {
+                               /* passwords with length "0" are valid! */
+                               cleartext_utf8_blob->data = NULL;
+                               cleartext_utf8_blob->length = 0;
+                       }
                }
+               g->cleartext_utf8 = cleartext_utf8_blob;
        }
 
        if (g->cleartext_utf16) {
@@ -1380,6 +2163,15 @@ static int setup_password_fields(struct setup_password_fields_io *io)
                                         struct loadparm_context);
        int ret;
 
+       ret = setup_last_set_field(io);
+       if (ret != LDB_SUCCESS) {
+               return ret;
+       }
+
+       if (!io->ac->update_password) {
+               return LDB_SUCCESS;
+       }
+
        /* transform the old password (for password changes) */
        ret = setup_given_passwords(io, &io->og);
        if (ret != LDB_SUCCESS) {
@@ -1419,64 +2211,236 @@ static int setup_password_fields(struct setup_password_fields_io *io)
                return ret;
        }
 
-       ret = setup_last_set_field(io);
-       if (ret != LDB_SUCCESS) {
-               return ret;
+       return LDB_SUCCESS;
+}
+
+static int setup_smartcard_reset(struct setup_password_fields_io *io)
+{
+       struct ldb_context *ldb = ldb_module_get_ctx(io->ac->module);
+       struct loadparm_context *lp_ctx = talloc_get_type(
+               ldb_get_opaque(ldb, "loadparm"), struct loadparm_context);
+       struct supplementalCredentialsBlob scb = { .__ndr_size = 0 };
+       enum ndr_err_code ndr_err;
+
+       if (!io->ac->smartcard_reset) {
+               return LDB_SUCCESS;
+       }
+
+       io->g.nt_hash = talloc(io->ac, struct samr_Password);
+       if (io->g.nt_hash == NULL) {
+               return ldb_module_oom(io->ac->module);
        }
+       generate_secret_buffer(io->g.nt_hash->hash,
+                              sizeof(io->g.nt_hash->hash));
+       io->g.nt_history_len = 0;
 
+       if (lpcfg_lanman_auth(lp_ctx)) {
+               io->g.lm_hash = talloc(io->ac, struct samr_Password);
+               if (io->g.lm_hash == NULL) {
+                       return ldb_module_oom(io->ac->module);
+               }
+               generate_secret_buffer(io->g.lm_hash->hash,
+                                      sizeof(io->g.lm_hash->hash));
+       } else {
+               io->g.lm_hash = NULL;
+       }
+       io->g.lm_history_len = 0;
+
+       /*
+        * We take the "old" value and store it
+        * with num_packages = 0.
+        *
+        * On "add" we have scb.sub.signature == 0, which
+        * results in:
+        *
+        * [0000] 00 00 00 00 00 00 00 00   00 00 00 00 00
+        *
+        * On modify it's likely to be scb.sub.signature ==
+        * SUPPLEMENTAL_CREDENTIALS_SIGNATURE (0x0050), which results in
+        * something like:
+        *
+        * [0000] 00 00 00 00 62 00 00 00   00 00 00 00 20 00 20 00
+        * [0010] 20 00 20 00 20 00 20 00   20 00 20 00 20 00 20 00
+        * [0020] 20 00 20 00 20 00 20 00   20 00 20 00 20 00 20 00
+        * [0030] 20 00 20 00 20 00 20 00   20 00 20 00 20 00 20 00
+        * [0040] 20 00 20 00 20 00 20 00   20 00 20 00 20 00 20 00
+        * [0050] 20 00 20 00 20 00 20 00   20 00 20 00 20 00 20 00
+        * [0060] 20 00 20 00 20 00 20 00   20 00 20 00 50 00 00
+        *
+        * See https://bugzilla.samba.org/show_bug.cgi?id=11441
+        * and ndr_{push,pull}_supplementalCredentialsSubBlob().
+        */
+       scb = io->o.scb;
+       scb.sub.num_packages = 0;
+
+       /*
+        * setup 'supplementalCredentials' value without packages
+        */
+       ndr_err = ndr_push_struct_blob(&io->g.supplemental, io->ac,
+                                      &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(ldb,
+                                      "setup_smartcard_reset: "
+                                      "failed to push supplementalCredentialsBlob: %s",
+                                      nt_errstr(status));
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       io->ac->update_password = true;
        return LDB_SUCCESS;
 }
 
+static int make_error_and_update_badPwdCount(struct setup_password_fields_io *io)
+{
+       struct ldb_context *ldb = ldb_module_get_ctx(io->ac->module);
+       struct ldb_message *mod_msg = NULL;
+       NTSTATUS status;
+       int ret;
+
+       status = dsdb_update_bad_pwd_count(io->ac, ldb,
+                                          io->ac->search_res->message,
+                                          io->ac->dom_res->message,
+                                          &mod_msg);
+       if (!NT_STATUS_IS_OK(status)) {
+               goto done;
+       }
+
+       if (mod_msg == NULL) {
+               goto done;
+       }
+
+       /*
+        * OK, horrible semantics ahead.
+        *
+        * - We need to abort any existing transaction
+        * - create a transaction arround the badPwdCount update
+        * - re-open the transaction so the upper layer
+        *   doesn't know what happened.
+        *
+        * This is needed because returning an error to the upper
+        * layer will cancel the transaction and undo the badPwdCount
+        * update.
+        */
+
+       /*
+        * Checking errors here is a bit pointless.
+        * What can we do if we can't end the transaction?
+        */
+       ret = ldb_next_del_trans(io->ac->module);
+       if (ret != LDB_SUCCESS) {
+               ldb_debug(ldb, LDB_DEBUG_FATAL,
+                         "Failed to abort transaction prior to update of badPwdCount of %s: %s",
+                         ldb_dn_get_linearized(io->ac->search_res->message->dn),
+                         ldb_errstring(ldb));
+               /*
+                * just return the original error
+                */
+               goto done;
+       }
+
+       /* Likewise, what should we do if we can't open a new transaction? */
+       ret = ldb_next_start_trans(io->ac->module);
+       if (ret != LDB_SUCCESS) {
+               ldb_debug(ldb, LDB_DEBUG_ERROR,
+                         "Failed to open transaction to update badPwdCount of %s: %s",
+                         ldb_dn_get_linearized(io->ac->search_res->message->dn),
+                         ldb_errstring(ldb));
+               /*
+                * just return the original error
+                */
+               goto done;
+       }
+
+       ret = dsdb_module_modify(io->ac->module, mod_msg,
+                                DSDB_FLAG_NEXT_MODULE,
+                                io->ac->req);
+       if (ret != LDB_SUCCESS) {
+               ldb_debug(ldb, LDB_DEBUG_ERROR,
+                         "Failed to update badPwdCount of %s: %s",
+                         ldb_dn_get_linearized(io->ac->search_res->message->dn),
+                         ldb_errstring(ldb));
+               /*
+                * We can only ignore this...
+                */
+       }
+
+       ret = ldb_next_end_trans(io->ac->module);
+       if (ret != LDB_SUCCESS) {
+               ldb_debug(ldb, LDB_DEBUG_ERROR,
+                         "Failed to close transaction to update badPwdCount of %s: %s",
+                         ldb_dn_get_linearized(io->ac->search_res->message->dn),
+                         ldb_errstring(ldb));
+               /*
+                * We can only ignore this...
+                */
+       }
+
+       ret = ldb_next_start_trans(io->ac->module);
+       if (ret != LDB_SUCCESS) {
+               ldb_debug(ldb, LDB_DEBUG_ERROR,
+                         "Failed to open transaction after update of badPwdCount of %s: %s",
+                         ldb_dn_get_linearized(io->ac->search_res->message->dn),
+                         ldb_errstring(ldb));
+               /*
+                * We can only ignore this...
+                */
+       }
+
+done:
+       ret = LDB_ERR_CONSTRAINT_VIOLATION;
+       ldb_asprintf_errstring(ldb,
+                              "%08X: %s - check_password_restrictions: "
+                              "The old password specified doesn't match!",
+                              W_ERROR_V(WERR_INVALID_PASSWORD),
+                              ldb_strerror(ret));
+       return ret;
+}
+
 static int check_password_restrictions(struct setup_password_fields_io *io)
 {
-       struct ldb_context *ldb;
+       struct ldb_context *ldb = ldb_module_get_ctx(io->ac->module);
        int ret;
-       enum samr_ValidationStatus stat;
+       struct loadparm_context *lp_ctx =
+               lp_ctx = talloc_get_type(ldb_get_opaque(ldb, "loadparm"),
+                                        struct loadparm_context);
 
-       ldb = ldb_module_get_ctx(io->ac->module);
+       if (!io->ac->update_password) {
+               return LDB_SUCCESS;
+       }
 
        /* 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->ac->pwd_reset) {
+               bool nt_hash_checked = false;
+
+               /* we need the 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!");
+                               "You need to provide the old password in order "
+                               "to change it!");
                        return LDB_ERR_UNWILLING_TO_PERFORM;
                }
 
+               /* The password modify through the NT hash is encouraged and
+                  has no problems at all */
                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;
+                       if (!io->o.nt_hash || memcmp(io->og.nt_hash->hash, io->o.nt_hash->hash, 16) != 0) {
+                               return make_error_and_update_badPwdCount(io);
                        }
 
-                       /* 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) {
-                       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;
-                       }
+                       nt_hash_checked = true;
+               }
 
-                       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;
+               /* But it is also possible to change a password by the LM hash
+                * alone for compatibility reasons. This check is optional if
+                * the NT hash was already checked - otherwise it's mandatory.
+                * (as the SAMR operations request it). */
+               if (io->og.lm_hash) {
+                       if ((!io->o.lm_hash && !nt_hash_checked)
+                           || (io->o.lm_hash && memcmp(io->og.lm_hash->hash, io->o.lm_hash->hash, 16) != 0)) {
+                               return make_error_and_update_badPwdCount(io);
                        }
                }
        }
@@ -1486,43 +2450,64 @@ static int check_password_restrictions(struct setup_password_fields_io *io)
                return LDB_SUCCESS;
        }
 
+       /* 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) &&
+           !io->ac->pwd_reset)
+       {
+               ret = LDB_ERR_CONSTRAINT_VIOLATION;
+               ldb_asprintf_errstring(ldb,
+                       "%08X: %s - check_password_restrictions: "
+                       "password is too young to change!",
+                       W_ERROR_V(WERR_PASSWORD_RESTRICTION),
+                       ldb_strerror(ret));
+               return ret;
+       }
+
        /*
         * 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) {
+               enum samr_ValidationStatus vstat;
+               vstat = samdb_check_password(io->ac, lp_ctx,
+                                            io->n.cleartext_utf8,
+                                            io->ac->status->domain_data.pwdProperties,
+                                            io->ac->status->domain_data.minPwdLength);
+               switch (vstat) {
                case SAMR_VALIDATION_STATUS_SUCCESS:
                                /* perfect -> proceed! */
                        break;
 
                case SAMR_VALIDATION_STATUS_PWD_TOO_SHORT:
+                       ret = LDB_ERR_CONSTRAINT_VIOLATION;
                        ldb_asprintf_errstring(ldb,
-                               "check_password_restrictions: "
-                               "the password is too short. It should be equal or longer than %i characters!",
+                               "%08X: %s - check_password_restrictions: "
+                               "the password is too short. It should be equal or longer than %u characters!",
+                               W_ERROR_V(WERR_PASSWORD_RESTRICTION),
+                               ldb_strerror(ret),
                                io->ac->status->domain_data.minPwdLength);
-
                        io->ac->status->reject_reason = SAM_PWD_CHANGE_PASSWORD_TOO_SHORT;
-                       return LDB_ERR_CONSTRAINT_VIOLATION;
+                       return ret;
 
                case SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH:
+                       ret = LDB_ERR_CONSTRAINT_VIOLATION;
                        ldb_asprintf_errstring(ldb,
-                               "check_password_restrictions: "
-                               "the password does not meet the complexity criterias!");
+                               "%08X: %s - check_password_restrictions: "
+                               "the password does not meet the complexity criteria!",
+                               W_ERROR_V(WERR_PASSWORD_RESTRICTION),
+                               ldb_strerror(ret));
                        io->ac->status->reject_reason = SAM_PWD_CHANGE_NOT_COMPLEX;
-
-                       return LDB_ERR_CONSTRAINT_VIOLATION;
+                       return ret;
 
                default:
+                       ret = LDB_ERR_CONSTRAINT_VIOLATION;
                        ldb_asprintf_errstring(ldb,
-                               "check_password_restrictions: "
-                               "the password doesn't fit by a certain reason!");
-
-                       return LDB_ERR_CONSTRAINT_VIOLATION;
+                               "%08X: %s - check_password_restrictions: "
+                               "the password doesn't fit due to a miscellaneous restriction!",
+                               W_ERROR_V(WERR_PASSWORD_RESTRICTION),
+                               ldb_strerror(ret));
+                       return ret;
                }
        }
 
@@ -1537,13 +2522,14 @@ static int check_password_restrictions(struct setup_password_fields_io *io)
                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) {
+                               ret = LDB_ERR_CONSTRAINT_VIOLATION;
                                ldb_asprintf_errstring(ldb,
-                                       "check_password_restrictions: "
-                                       "the password was already used (in history)!");
-
+                                       "%08X: %s - check_password_restrictions: "
+                                       "the password was already used (in history)!",
+                                       W_ERROR_V(WERR_PASSWORD_RESTRICTION),
+                                       ldb_strerror(ret));
                                io->ac->status->reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
-
-                               return LDB_ERR_CONSTRAINT_VIOLATION;
+                               return ret;
                        }
                }
        }
@@ -1553,64 +2539,282 @@ static int check_password_restrictions(struct setup_password_fields_io *io)
 
                /* 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);
+                       ret = memcmp(io->n.lm_hash, io->o.lm_history[i].hash, 16);
                        if (ret == 0) {
+                               ret = LDB_ERR_CONSTRAINT_VIOLATION;
                                ldb_asprintf_errstring(ldb,
-                                       "check_password_restrictions: "
-                                       "the password was already used (in history)!");
-
+                                       "%08X: %s - check_password_restrictions: "
+                                       "the password was already used (in history)!",
+                                       W_ERROR_V(WERR_PASSWORD_RESTRICTION),
+                                       ldb_strerror(ret));
                                io->ac->status->reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
-
-                               return LDB_ERR_CONSTRAINT_VIOLATION;
+                               return ret;
                        }
                }
        }
 
        /* are all password changes disallowed? */
        if (io->ac->status->domain_data.pwdProperties & DOMAIN_REFUSE_PASSWORD_CHANGE) {
+               ret = LDB_ERR_CONSTRAINT_VIOLATION;
                ldb_asprintf_errstring(ldb,
-                       "check_password_restrictions: "
-                       "password changes disabled!");
-               return LDB_ERR_CONSTRAINT_VIOLATION;
+                       "%08X: %s - check_password_restrictions: "
+                       "password changes disabled!",
+                       W_ERROR_V(WERR_PASSWORD_RESTRICTION),
+                       ldb_strerror(ret));
+               return ret;
        }
 
        /* can this user change the password? */
        if (io->u.userAccountControl & UF_PASSWD_CANT_CHANGE) {
+               ret = LDB_ERR_CONSTRAINT_VIOLATION;
                ldb_asprintf_errstring(ldb,
-                       "check_password_restrictions: "
-                       "password can't be changed on this account!");
-               return LDB_ERR_CONSTRAINT_VIOLATION;
+                       "%08X: %s - check_password_restrictions: "
+                       "password can't be changed on this account!",
+                       W_ERROR_V(WERR_PASSWORD_RESTRICTION),
+                       ldb_strerror(ret));
+               return ret;
        }
 
-       /* 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;
+       return LDB_SUCCESS;
+}
+
+static int update_final_msg(struct setup_password_fields_io *io)
+{
+       struct ldb_context *ldb = ldb_module_get_ctx(io->ac->module);
+       int ret;
+       int el_flags = 0;
+       bool update_password = io->ac->update_password;
+       bool update_scb = io->ac->update_password;
+
+       /*
+        * If we add a user without initial password,
+        * we need to add replication meta data for
+        * following attributes:
+        * - unicodePwd
+        * - dBCSPwd
+        * - ntPwdHistory
+        * - lmPwdHistory
+        *
+        * If we add a user with initial password or a
+        * password is changed of an existing user,
+        * we need to replace the following attributes
+        * with a forced meta data update, e.g. also
+        * when updating an empty attribute with an empty value:
+        * - unicodePwd
+        * - dBCSPwd
+        * - ntPwdHistory
+        * - lmPwdHistory
+        * - supplementalCredentials
+        */
+
+       switch (io->ac->req->operation) {
+       case LDB_ADD:
+               update_password = true;
+               el_flags |= DSDB_FLAG_INTERNAL_FORCE_META_DATA;
+               break;
+       case LDB_MODIFY:
+               el_flags |= LDB_FLAG_MOD_REPLACE;
+               el_flags |= DSDB_FLAG_INTERNAL_FORCE_META_DATA;
+               break;
+       default:
+               return ldb_module_operr(io->ac->module);
+       }
+
+       if (update_password) {
+               ret = ldb_msg_add_empty(io->ac->update_msg,
+                                       "unicodePwd",
+                                       el_flags, NULL);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
+               }
+               ret = ldb_msg_add_empty(io->ac->update_msg,
+                                       "dBCSPwd",
+                                       el_flags, NULL);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
+               }
+               ret = ldb_msg_add_empty(io->ac->update_msg,
+                                       "ntPwdHistory",
+                                       el_flags, NULL);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
+               }
+               ret = ldb_msg_add_empty(io->ac->update_msg,
+                                       "lmPwdHistory",
+                                       el_flags, NULL);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
+               }
+       }
+       if (update_scb) {
+               ret = ldb_msg_add_empty(io->ac->update_msg,
+                                       "supplementalCredentials",
+                                       el_flags, NULL);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
+               }
+       }
+       if (io->ac->update_lastset) {
+               ret = ldb_msg_add_empty(io->ac->update_msg,
+                                       "pwdLastSet",
+                                       el_flags, NULL);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
+               }
+       }
+
+       if (io->g.nt_hash != NULL) {
+               ret = samdb_msg_add_hash(ldb, io->ac,
+                                        io->ac->update_msg,
+                                        "unicodePwd",
+                                        io->g.nt_hash);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
+               }
+       }
+       if (io->g.lm_hash != NULL) {
+               ret = samdb_msg_add_hash(ldb, io->ac,
+                                        io->ac->update_msg,
+                                        "dBCSPwd",
+                                        io->g.lm_hash);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
+               }
+       }
+       if (io->g.nt_history_len > 0) {
+               ret = samdb_msg_add_hashes(ldb, io->ac,
+                                          io->ac->update_msg,
+                                          "ntPwdHistory",
+                                          io->g.nt_history,
+                                          io->g.nt_history_len);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
+               }
+       }
+       if (io->g.lm_history_len > 0) {
+               ret = samdb_msg_add_hashes(ldb, io->ac,
+                                          io->ac->update_msg,
+                                          "lmPwdHistory",
+                                          io->g.lm_history,
+                                          io->g.lm_history_len);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
+               }
+       }
+       if (io->g.supplemental.length > 0) {
+               ret = ldb_msg_add_value(io->ac->update_msg,
+                                       "supplementalCredentials",
+                                       &io->g.supplemental, NULL);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
+               }
+       }
+       if (io->ac->update_lastset) {
+               ret = samdb_msg_add_uint64(ldb, io->ac,
+                                          io->ac->update_msg,
+                                          "pwdLastSet",
+                                          io->g.last_set);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
+               }
+       }
+
+       return LDB_SUCCESS;
+}
+
+/*
+ * This is intended for use by the "password_hash" module since there
+ * password changes can be specified through one message element with the
+ * new password (to set) and another one with the old password (to unset).
+ *
+ * The first which sets a password (new value) can have flags
+ * (LDB_FLAG_MOD_ADD, LDB_FLAG_MOD_REPLACE) but also none (on "add" operations
+ * for entries). The latter (old value) has always specified
+ * LDB_FLAG_MOD_DELETE.
+ *
+ * Returns LDB_ERR_CONSTRAINT_VIOLATION and LDB_ERR_UNWILLING_TO_PERFORM if
+ * matching message elements are malformed in respect to the set/change rules.
+ * Otherwise it returns LDB_SUCCESS.
+ */
+static int msg_find_old_and_new_pwd_val(const struct ldb_message *msg,
+                                       const char *name,
+                                       enum ldb_request_type operation,
+                                       const struct ldb_val **new_val,
+                                       const struct ldb_val **old_val)
+{
+       unsigned int i;
+
+       *new_val = NULL;
+       *old_val = NULL;
+
+       if (msg == NULL) {
+               return LDB_SUCCESS;
+       }
+
+       for (i = 0; i < msg->num_elements; i++) {
+               if (ldb_attr_cmp(msg->elements[i].name, name) != 0) {
+                       continue;
+               }
+
+               if ((operation == LDB_MODIFY) &&
+                   (LDB_FLAG_MOD_TYPE(msg->elements[i].flags) == LDB_FLAG_MOD_DELETE)) {
+                       /* 0 values are allowed */
+                       if (msg->elements[i].num_values == 1) {
+                               *old_val = &msg->elements[i].values[0];
+                       } else if (msg->elements[i].num_values > 1) {
+                               return LDB_ERR_CONSTRAINT_VIOLATION;
+                       }
+               } else if ((operation == LDB_MODIFY) &&
+                          (LDB_FLAG_MOD_TYPE(msg->elements[i].flags) == LDB_FLAG_MOD_REPLACE)) {
+                       if (msg->elements[i].num_values > 0) {
+                               *new_val = &msg->elements[i].values[msg->elements[i].num_values - 1];
+                       } else {
+                               return LDB_ERR_UNWILLING_TO_PERFORM;
+                       }
+               } else {
+                       /* Add operations and LDB_FLAG_MOD_ADD */
+                       if (msg->elements[i].num_values > 0) {
+                               *new_val = &msg->elements[i].values[msg->elements[i].num_values - 1];
+                       } else {
+                               return LDB_ERR_CONSTRAINT_VIOLATION;
+                       }
+               }
        }
 
        return LDB_SUCCESS;
 }
 
 static int setup_io(struct ph_context *ac, 
-                   const struct ldb_message *orig_msg,
-                   const struct ldb_message *searched_msg, 
+                   const struct ldb_message *client_msg,
+                   const struct ldb_message *existing_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);
-       struct loadparm_context *lp_ctx =
-               lp_ctx = talloc_get_type(ldb_get_opaque(ldb, "loadparm"),
-                                        struct loadparm_context);
+       struct loadparm_context *lp_ctx = talloc_get_type(
+               ldb_get_opaque(ldb, "loadparm"), struct loadparm_context);
        int ret;
+       const struct ldb_message *info_msg = NULL;
+       struct dom_sid *account_sid = NULL;
+       int rodc_krbtgt = 0;
 
        ZERO_STRUCTP(io);
 
        /* Some operations below require kerberos contexts */
 
+       if (existing_msg != NULL) {
+               /*
+                * This is a modify operation
+                */
+               info_msg = existing_msg;
+       } else {
+               /*
+                * This is an add operation
+                */
+               info_msg = client_msg;
+       }
+
        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_operr(ldb);
@@ -1618,42 +2822,121 @@ static int setup_io(struct ph_context *ac,
 
        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");
+       io->u.userAccountControl        = ldb_msg_find_attr_as_uint(info_msg,
+                                                                   "userAccountControl", 0);
+       if (info_msg == existing_msg) {
+               /*
+                * We only take pwdLastSet from the existing object
+                * otherwise we leave it as 0.
+                *
+                * If no attribute is available, e.g. on deleted objects
+                * we remember that as UINT64_MAX.
+                */
+               io->u.pwdLastSet = samdb_result_nttime(info_msg, "pwdLastSet",
+                                                      UINT64_MAX);
+       }
+       io->u.sAMAccountName            = ldb_msg_find_attr_as_string(info_msg,
+                                                                     "sAMAccountName", NULL);
+       io->u.user_principal_name       = ldb_msg_find_attr_as_string(info_msg,
+                                                                     "userPrincipalName", NULL);
+       io->u.is_computer               = ldb_msg_check_string_attribute(info_msg, "objectClass", "computer");
+
+       /* Ensure it has an objectSID too */
+       account_sid = samdb_result_dom_sid(ac, info_msg, "objectSid");
+       if (account_sid != NULL) {
+               NTSTATUS status;
+               uint32_t rid = 0;
+
+               status = dom_sid_split_rid(account_sid, account_sid, NULL, &rid);
+               if (NT_STATUS_IS_OK(status)) {
+                       if (rid == DOMAIN_RID_KRBTGT) {
+                               io->u.is_krbtgt = true;
+                       }
+               }
+       }
+
+       rodc_krbtgt = ldb_msg_find_attr_as_int(info_msg,
+                       "msDS-SecondaryKrbTgtNumber", 0);
+       if (rodc_krbtgt != 0) {
+               io->u.is_krbtgt = true;
+       }
 
        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));
+                                      ldb_dn_get_linearized(info_msg->dn));
 
                return LDB_ERR_CONSTRAINT_VIOLATION;
        }
 
+       if (io->u.userAccountControl & UF_INTERDOMAIN_TRUST_ACCOUNT) {
+               struct ldb_control *permit_trust = ldb_request_get_control(ac->req,
+                               DSDB_CONTROL_PERMIT_INTERDOMAIN_TRUST_UAC_OID);
+
+               if (permit_trust == NULL) {
+                       ret = LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
+                       ldb_asprintf_errstring(ldb,
+                               "%08X: %s - setup_io: changing the interdomain trust password "
+                               "on %s not allowed via LDAP. Use LSA or NETLOGON",
+                               W_ERROR_V(WERR_ACCESS_DENIED),
+                               ldb_strerror(ret),
+                               ldb_dn_get_linearized(info_msg->dn));
+                       return ret;
+               }
+       }
+
        /* 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 */
+       if (io->u.is_krbtgt) {
                io->u.restrictions = 0;
+               io->ac->status->domain_data.pwdHistoryLength =
+                       MAX(io->ac->status->domain_data.pwdHistoryLength, 3);
        }
 
-       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;
+       if (ac->userPassword) {
+               ret = msg_find_old_and_new_pwd_val(client_msg, "userPassword",
+                                                  ac->req->operation,
+                                                  &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;
+               }
+       }
+
+       if (io->n.cleartext_utf8 != NULL) {
+               struct ldb_val *cleartext_utf8_blob;
+               char *p;
+
+               cleartext_utf8_blob = talloc(io->ac, struct ldb_val);
+               if (!cleartext_utf8_blob) {
+                       return ldb_oom(ldb);
+               }
+
+               *cleartext_utf8_blob = *io->n.cleartext_utf8;
+
+               /* make sure we have a null terminated string */
+               p = talloc_strndup(cleartext_utf8_blob,
+                                  (const char *)io->n.cleartext_utf8->data,
+                                  io->n.cleartext_utf8->length);
+               if ((p == NULL) && (io->n.cleartext_utf8->length > 0)) {
+                       return ldb_oom(ldb);
+               }
+               cleartext_utf8_blob->data = (uint8_t *)p;
+
+               io->n.cleartext_utf8 = cleartext_utf8_blob;
        }
 
-       ret = samdb_msg_find_old_and_new_ldb_val(orig_msg, "clearTextPassword",
-               &io->n.cleartext_utf16, &io->og.cleartext_utf16);
+       ret = msg_find_old_and_new_pwd_val(client_msg, "clearTextPassword",
+                                          ac->req->operation,
+                                          &io->n.cleartext_utf16,
+                                          &io->og.cleartext_utf16);
        if (ret != LDB_SUCCESS) {
                ldb_asprintf_errstring(ldb,
                        "setup_io: "
@@ -1674,8 +2957,10 @@ static int setup_io(struct ph_context *ac,
           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);
+       ret = msg_find_old_and_new_pwd_val(client_msg, "unicodePwd",
+                                          ac->req->operation,
+                                          &quoted_utf16,
+                                          &old_quoted_utf16);
        if (ret != LDB_SUCCESS) {
                ldb_asprintf_errstring(ldb,
                        "setup_io: "
@@ -1684,7 +2969,8 @@ static int setup_io(struct ph_context *ac,
        }
 
        /* Checks and converts the actual "unicodePwd" attribute */
-       if (quoted_utf16 &&
+       if (!ac->hash_values &&
+           quoted_utf16 &&
            quoted_utf16->length >= 4 &&
            quoted_utf16->data[0] == '"' &&
            quoted_utf16->data[1] == 0 &&
@@ -1740,7 +3026,8 @@ static int setup_io(struct ph_context *ac,
        }
 
        /* Checks and converts the previous "unicodePwd" attribute */
-       if (old_quoted_utf16 &&
+       if (!ac->hash_values &&
+           old_quoted_utf16 &&
            old_quoted_utf16->length >= 4 &&
            old_quoted_utf16->data[0] == '"' &&
            old_quoted_utf16->data[1] == 0 &&
@@ -1789,8 +3076,9 @@ static int setup_io(struct ph_context *ac,
 
        /* 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);
+       ret = msg_find_old_and_new_pwd_val(client_msg, "dBCSPwd",
+                                          ac->req->operation,
+                                          &lm_hash, &old_lm_hash);
        if (ret != LDB_SUCCESS) {
                ldb_asprintf_errstring(ldb,
                        "setup_io: "
@@ -1818,6 +3106,27 @@ static int setup_io(struct ph_context *ac,
                       sizeof(io->og.lm_hash->hash)));
        }
 
+       /*
+        * Handles the password change control if it's specified. It has the
+        * precedance and overrides already specified old password values of
+        * change requests (but that shouldn't happen since the control is
+        * fully internal and only used in conjunction with replace requests!).
+        */
+       if (ac->change != NULL) {
+               io->og.nt_hash = NULL;
+               if (ac->change->old_nt_pwd_hash != NULL) {
+                       io->og.nt_hash = talloc_memdup(io->ac,
+                                                      ac->change->old_nt_pwd_hash,
+                                                      sizeof(struct samr_Password));
+               }
+               io->og.lm_hash = NULL;
+               if (lpcfg_lanman_auth(lp_ctx) && (ac->change->old_lm_pwd_hash != NULL)) {
+                       io->og.lm_hash = talloc_memdup(io->ac,
+                                                      ac->change->old_lm_pwd_hash,
+                                                      sizeof(struct samr_Password));
+               }
+       }
+
        /* 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)
@@ -1840,11 +3149,18 @@ static int setup_io(struct ph_context *ac,
        /* refuse the change if someone tries to set/change the password by
         * the lanman hash alone and we've deactivated that mechanism. This
         * would end in an account without any password! */
-       if ((!io->n.cleartext_utf8) && (!io->n.cleartext_utf16)
+       if (io->ac->update_password
+           && (!io->n.cleartext_utf8) && (!io->n.cleartext_utf16)
            && (!io->n.nt_hash) && (!io->n.lm_hash)) {
                ldb_asprintf_errstring(ldb,
                        "setup_io: "
-                       "The password change/set operations performed using the LAN Manager hash alone are deactivated!");
+                       "It's not possible to delete the password (changes using the LAN Manager hash alone could be deactivated)!");
+               /* on "userPassword" and "clearTextPassword" we've to return
+                * something different, since these are virtual attributes */
+               if ((ldb_msg_find_element(client_msg, "userPassword") != NULL) ||
+                   (ldb_msg_find_element(client_msg, "clearTextPassword") != NULL)) {
+                       return LDB_ERR_CONSTRAINT_VIOLATION;
+               }
                return LDB_ERR_UNWILLING_TO_PERFORM;
        }
 
@@ -1867,25 +3183,14 @@ static int setup_io(struct ph_context *ac,
                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
+                   || io->og.nt_hash || io->og.lm_hash) {
+                       /* If we have an old password specified then for sure it
                         * is a user "password change" */
                        ac->pwd_reset = false;
                } else {
@@ -1897,14 +3202,131 @@ static int setup_io(struct ph_context *ac,
                return ldb_operr(ldb);
        }
 
+       if (io->u.is_krbtgt) {
+               size_t min = 196;
+               size_t max = 255;
+               size_t diff = max - min;
+               size_t len = max;
+               struct ldb_val *krbtgt_utf16 = NULL;
+
+               if (!ac->pwd_reset) {
+                       return dsdb_module_werror(ac->module,
+                                       LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS,
+                                       WERR_DS_ATT_ALREADY_EXISTS,
+                                       "Password change on krbtgt not permitted!");
+               }
+
+               if (io->n.cleartext_utf16 == NULL) {
+                       return dsdb_module_werror(ac->module,
+                                       LDB_ERR_UNWILLING_TO_PERFORM,
+                                       WERR_DS_INVALID_ATTRIBUTE_SYNTAX,
+                                       "Password reset on krbtgt requires UTF16!");
+               }
+
+               /*
+                * Instead of taking the callers value,
+                * we just generate a new random value here.
+                *
+                * Include null termination in the array.
+                */
+               if (diff > 0) {
+                       size_t tmp;
+
+                       generate_random_buffer((uint8_t *)&tmp, sizeof(tmp));
+
+                       tmp %= diff;
+
+                       len = min + tmp;
+               }
+
+               krbtgt_utf16 = talloc_zero(io->ac, struct ldb_val);
+               if (krbtgt_utf16 == NULL) {
+                       return ldb_oom(ldb);
+               }
+
+               *krbtgt_utf16 = data_blob_talloc_zero(krbtgt_utf16,
+                                                     (len+1)*2);
+               if (krbtgt_utf16->data == NULL) {
+                       return ldb_oom(ldb);
+               }
+               krbtgt_utf16->length = len * 2;
+               generate_secret_buffer(krbtgt_utf16->data,
+                                      krbtgt_utf16->length);
+               io->n.cleartext_utf16 = krbtgt_utf16;
+       }
+
+       if (existing_msg != NULL) {
+               NTSTATUS status;
+
+               if (ac->pwd_reset) {
+                       /* Get the old password from the database */
+                       status = samdb_result_passwords_no_lockout(ac,
+                                                                  lp_ctx,
+                                                                  existing_msg,
+                                                                  &io->o.lm_hash,
+                                                                  &io->o.nt_hash);
+               } else {
+                       /* Get the old password from the database */
+                       status = samdb_result_passwords(ac,
+                                                       lp_ctx,
+                                                       existing_msg,
+                                                       &io->o.lm_hash,
+                                                       &io->o.nt_hash);
+               }
+
+               if (NT_STATUS_EQUAL(status, NT_STATUS_ACCOUNT_LOCKED_OUT)) {
+                       return dsdb_module_werror(ac->module,
+                                                 LDB_ERR_CONSTRAINT_VIOLATION,
+                                                 WERR_ACCOUNT_LOCKED_OUT,
+                                                 "Password change not permitted,"
+                                                 " account locked out!");
+               }
+
+               if (!NT_STATUS_IS_OK(status)) {
+                       /*
+                        * This only happens if the database has gone weird,
+                        * not if we are just missing the passwords
+                        */
+                       return ldb_operr(ldb);
+               }
+
+               io->o.nt_history_len = samdb_result_hashes(ac, existing_msg,
+                                                          "ntPwdHistory",
+                                                          &io->o.nt_history);
+               io->o.lm_history_len = samdb_result_hashes(ac, existing_msg,
+                                                          "lmPwdHistory",
+                                                          &io->o.lm_history);
+               io->o.supplemental = ldb_msg_find_ldb_val(existing_msg,
+                                                         "supplementalCredentials");
+
+               if (io->o.supplemental != NULL) {
+                       enum ndr_err_code ndr_err;
+
+                       ndr_err = ndr_pull_struct_blob_all(io->o.supplemental, io->ac,
+                                       &io->o.scb,
+                                       (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
+                       if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
+                               status = ndr_map_error2ntstatus(ndr_err);
+                               ldb_asprintf_errstring(ldb,
+                                               "setup_io: failed to pull "
+                                               "old supplementalCredentialsBlob: %s",
+                                               nt_errstr(status));
+                               return LDB_ERR_OPERATIONS_ERROR;
+                       }
+               }
+       }
+
        return LDB_SUCCESS;
 }
 
 static struct ph_context *ph_init_context(struct ldb_module *module,
-                                         struct ldb_request *req)
+                                         struct ldb_request *req,
+                                         bool userPassword,
+                                         bool update_password)
 {
        struct ldb_context *ldb;
        struct ph_context *ac;
+       struct loadparm_context *lp_ctx = NULL;
 
        ldb = ldb_module_get_ctx(module);
 
@@ -1916,6 +3338,13 @@ static struct ph_context *ph_init_context(struct ldb_module *module,
 
        ac->module = module;
        ac->req = req;
+       ac->userPassword = userPassword;
+       ac->update_password = update_password;
+       ac->update_lastset = true;
+
+       lp_ctx = talloc_get_type_abort(ldb_get_opaque(ldb, "loadparm"),
+                                      struct loadparm_context);
+       ac->gpg_key_ids = lpcfg_password_hash_gpg_key_ids(lp_ctx);
 
        return ac;
 }
@@ -1944,14 +3373,52 @@ static void ph_apply_controls(struct ph_context *ac)
                ctrl->critical = false;
        }
 
-       ac->change_old_pw_checked = false;
        ctrl = ldb_request_get_control(ac->req,
-                                      DSDB_CONTROL_PASSWORD_CHANGE_OLD_PW_CHECKED_OID);
+                                      DSDB_CONTROL_PASSWORD_CHANGE_OID);
+       if (ctrl != NULL) {
+               ac->change = (struct dsdb_control_password_change *) ctrl->data;
+
+               /* Mark the "change" control as uncritical (done) */
+               ctrl->critical = false;
+       }
+
+       ac->pwd_last_set_bypass = false;
+       ctrl = ldb_request_get_control(ac->req,
+                               DSDB_CONTROL_PASSWORD_BYPASS_LAST_SET_OID);
+       if (ctrl != NULL) {
+               ac->pwd_last_set_bypass = true;
+
+               /* Mark the "bypass pwdLastSet" control as uncritical (done) */
+               ctrl->critical = false;
+       }
+
+       ac->pwd_last_set_default = false;
+       ctrl = ldb_request_get_control(ac->req,
+                               DSDB_CONTROL_PASSWORD_DEFAULT_LAST_SET_OID);
+       if (ctrl != NULL) {
+               ac->pwd_last_set_default = true;
+
+               /* Mark the "bypass pwdLastSet" control as uncritical (done) */
+               ctrl->critical = false;
+       }
+
+       ac->smartcard_reset = false;
+       ctrl = ldb_request_get_control(ac->req,
+                               DSDB_CONTROL_PASSWORD_USER_ACCOUNT_CONTROL_OID);
        if (ctrl != NULL) {
-               ac->change_old_pw_checked = true;
+               struct dsdb_control_password_user_account_control *uac = NULL;
+               uint32_t added_flags = 0;
+
+               uac = talloc_get_type_abort(ctrl->data,
+                       struct dsdb_control_password_user_account_control);
+
+               added_flags = uac->new_flags & ~uac->old_flags;
+
+               if (added_flags & UF_SMARTCARD_REQUIRED) {
+                       ac->smartcard_reset = true;
+               }
 
-               /* Mark the "change old password checked" control as uncritical
-                * (done) */
+               /* Mark the "smartcard required" control as uncritical (done) */
                ctrl->critical = false;
        }
 }
@@ -2007,7 +3474,7 @@ static int get_domain_data_callback(struct ldb_request *req,
        struct ldb_context *ldb;
        struct ph_context *ac;
        struct loadparm_context *lp_ctx;
-       int ret;
+       int ret = LDB_SUCCESS;
 
        ac = talloc_get_type(req->context, struct ph_context);
        ldb = ldb_module_get_ctx(ac->module);
@@ -2043,16 +3510,19 @@ static int get_domain_data_callback(struct ldb_request *req,
                }
 
                /* 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.pwdProperties =
+                       ldb_msg_find_attr_as_uint(ares->message, "pwdProperties", -1);
+               ac->status->domain_data.pwdHistoryLength =
+                       ldb_msg_find_attr_as_uint(ares->message, "pwdHistoryLength", -1);
+               ac->status->domain_data.maxPwdAge =
+                       ldb_msg_find_attr_as_int64(ares->message, "maxPwdAge", -1);
+               ac->status->domain_data.minPwdAge =
+                       ldb_msg_find_attr_as_int64(ares->message, "minPwdAge", -1);
+               ac->status->domain_data.minPwdLength =
+                       ldb_msg_find_attr_as_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
@@ -2067,6 +3537,15 @@ static int get_domain_data_callback(struct ldb_request *req,
 
                ac->status->reject_reason = SAM_PWD_CHANGE_NO_ERROR;
 
+               if (ac->dom_res != NULL) {
+                       talloc_free(ares);
+
+                       ldb_set_errstring(ldb, "Too many results");
+                       ret = LDB_ERR_OPERATIONS_ERROR;
+                       goto done;
+               }
+
+               ac->dom_res = talloc_steal(ac, ares);
                ret = LDB_SUCCESS;
                break;
 
@@ -2134,39 +3613,65 @@ static int build_domain_data_request(struct ph_context *ac)
                                              "maxPwdAge",
                                              "minPwdAge",
                                              "minPwdLength",
+                                             "lockoutThreshold",
+                                             "lockOutObservationWindow",
                                              NULL };
+       int ret;
 
        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);
+       ret = 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);
+       LDB_REQ_SET_LOCATION(ac->dom_req);
+       return ret;
 }
 
-static int password_hash_add(struct ldb_module *module, struct ldb_request *req)
+static int password_hash_needed(struct ldb_module *module,
+                               struct ldb_request *req,
+                               struct ph_context **_ac)
 {
-       struct ldb_context *ldb;
-       struct ph_context *ac;
-       struct ldb_message_element *userPasswordAttr, *clearTextPasswordAttr,
-               *ntAttr, *lmAttr;
-       int ret;
+       struct ldb_context *ldb = ldb_module_get_ctx(module);
+       const char *operation = NULL;
+       const struct ldb_message *msg = NULL;
+       struct ph_context *ac = NULL;
+       const char *passwordAttrs[] = {
+               "userPassword",
+               "clearTextPassword",
+               "unicodePwd",
+               "dBCSPwd",
+               NULL
+       };
+       const char **a = NULL;
+       unsigned int attr_cnt = 0;
        struct ldb_control *bypass = NULL;
+       struct ldb_control *uac_ctrl = NULL;
+       bool userPassword = dsdb_user_password_support(module, req, req);
+       bool update_password = false;
+       bool processing_needed = false;
 
-       ldb = ldb_module_get_ctx(module);
+       *_ac = NULL;
 
-       ldb_debug(ldb, LDB_DEBUG_TRACE, "password_hash_add\n");
+       ldb_debug(ldb, LDB_DEBUG_TRACE, "password_hash_needed\n");
 
-       if (ldb_dn_is_special(req->op.add.message->dn)) { /* do not manipulate our control entries */
+       switch (req->operation) {
+       case LDB_ADD:
+               operation = "add";
+               msg = req->op.add.message;
+               break;
+       case LDB_MODIFY:
+               operation = "modify";
+               msg = req->op.mod.message;
+               break;
+       default:
                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, ldb, LOCAL_BASE),
-                               req->op.add.message->dn) == 0) {
+       if (ldb_dn_is_special(msg->dn)) { /* do not manipulate our control entries */
                return ldb_next_request(module, req);
        }
 
@@ -2175,39 +3680,132 @@ static int password_hash_add(struct ldb_module *module, struct ldb_request *req)
        if (bypass != NULL) {
                /* Mark the "bypass" control as uncritical (done) */
                bypass->critical = false;
-               ldb_debug(ldb, LDB_DEBUG_TRACE, "password_hash_add (bypassing)\n");
-               return ldb_next_request(module, req);
+               ldb_debug(ldb, LDB_DEBUG_TRACE,
+                         "password_hash_needed(%s) (bypassing)\n",
+                         operation);
+               return password_hash_bypass(module, req);
        }
 
        /* nobody must touch password histories and 'supplementalCredentials' */
-       if (ldb_msg_find_element(req->op.add.message, "ntPwdHistory")) {
+       if (ldb_msg_find_element(msg, "ntPwdHistory")) {
                return LDB_ERR_UNWILLING_TO_PERFORM;
        }
-       if (ldb_msg_find_element(req->op.add.message, "lmPwdHistory")) {
+       if (ldb_msg_find_element(msg, "lmPwdHistory")) {
                return LDB_ERR_UNWILLING_TO_PERFORM;
        }
-       if (ldb_msg_find_element(req->op.add.message, "supplementalCredentials")) {
+       if (ldb_msg_find_element(msg, "supplementalCredentials")) {
                return LDB_ERR_UNWILLING_TO_PERFORM;
        }
 
-       /* If no part of this touches the 'userPassword' OR 'clearTextPassword'
-        * OR 'unicodePwd' OR 'dBCSPwd' 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.
+        * For password changes/set there should be a 'delete' or a 'modify'
+        * on these attributes.
+        */
+       for (a = passwordAttrs; *a != NULL; a++) {
+               if ((!userPassword) && (ldb_attr_cmp(*a, "userPassword") == 0)) {
+                       continue;
+               }
+
+               if (ldb_msg_find_element(msg, *a) != NULL) {
+                       /* MS-ADTS 3.1.1.3.1.5.2 */
+                       if ((ldb_attr_cmp(*a, "userPassword") == 0) &&
+                           (dsdb_functional_level(ldb) < DS_DOMAIN_FUNCTION_2003)) {
+                               return LDB_ERR_CONSTRAINT_VIOLATION;
+                       }
+
+                       ++attr_cnt;
+               }
+       }
+
+       if (attr_cnt > 0) {
+               update_password = true;
+               processing_needed = true;
+       }
+
+       if (ldb_msg_find_element(msg, "pwdLastSet")) {
+               processing_needed = true;
+       }
+
+       uac_ctrl = ldb_request_get_control(req,
+                               DSDB_CONTROL_PASSWORD_USER_ACCOUNT_CONTROL_OID);
+       if (uac_ctrl != NULL) {
+               struct dsdb_control_password_user_account_control *uac = NULL;
+               uint32_t added_flags = 0;
+
+               uac = talloc_get_type_abort(uac_ctrl->data,
+                       struct dsdb_control_password_user_account_control);
+
+               added_flags = uac->new_flags & ~uac->old_flags;
 
-       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 (added_flags & UF_SMARTCARD_REQUIRED) {
+                       processing_needed = true;
+               }
+       }
 
-       if ((!userPasswordAttr) && (!clearTextPasswordAttr) && (!ntAttr) && (!lmAttr)) {
+       if (!processing_needed) {
                return ldb_next_request(module, req);
        }
 
+       ac = ph_init_context(module, req, userPassword, update_password);
+       if (!ac) {
+               DEBUG(0,(__location__ ": %s\n", ldb_errstring(ldb)));
+               return ldb_operr(ldb);
+       }
+       ph_apply_controls(ac);
+
+       /*
+        * Make a copy in order to apply our modifications
+        * to the final update
+        */
+       ac->update_msg = ldb_msg_copy_shallow(ac, msg);
+       if (ac->update_msg == NULL) {
+               return ldb_oom(ldb);
+       }
+
+       /*
+        * Remove all password related attributes.
+        */
+       if (ac->userPassword) {
+               ldb_msg_remove_attr(ac->update_msg, "userPassword");
+       }
+       ldb_msg_remove_attr(ac->update_msg, "clearTextPassword");
+       ldb_msg_remove_attr(ac->update_msg, "unicodePwd");
+       ldb_msg_remove_attr(ac->update_msg, "ntPwdHistory");
+       ldb_msg_remove_attr(ac->update_msg, "dBCSPwd");
+       ldb_msg_remove_attr(ac->update_msg, "lmPwdHistory");
+       ldb_msg_remove_attr(ac->update_msg, "supplementalCredentials");
+       ldb_msg_remove_attr(ac->update_msg, "pwdLastSet");
+
+       *_ac = ac;
+       return LDB_SUCCESS;
+}
+
+static int password_hash_add(struct ldb_module *module, struct ldb_request *req)
+{
+       struct ldb_context *ldb = ldb_module_get_ctx(module);
+       struct ph_context *ac = NULL;
+       int ret;
+
+       ldb_debug(ldb, LDB_DEBUG_TRACE, "password_hash_add\n");
+
+       ret = password_hash_needed(module, req, &ac);
+       if (ret != LDB_SUCCESS) {
+               return ret;
+       }
+       if (ac == NULL) {
+               return ret;
+       }
+
        /* 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"))) {
 
+               TALLOC_FREE(ac);
+
                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'!");
@@ -2217,13 +3815,6 @@ static int password_hash_add(struct ldb_module *module, struct ldb_request *req)
                return ldb_next_request(module, req);
        }
 
-       ac = ph_init_context(module, req);
-       if (ac == NULL) {
-               DEBUG(0,(__location__ ": %s\n", ldb_errstring(ldb)));
-               return ldb_operr(ldb);
-       }
-       ph_apply_controls(ac);
-
        /* get user domain data */
        ret = build_domain_data_request(ac);
        if (ret != LDB_SUCCESS) {
@@ -2235,32 +3826,17 @@ static int password_hash_add(struct ldb_module *module, struct ldb_request *req)
 
 static int password_hash_add_do_add(struct ph_context *ac)
 {
-       struct ldb_context *ldb;
+       struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
        struct ldb_request *down_req;
-       struct ldb_message *msg;
        struct setup_password_fields_io io;
        int ret;
 
        /* Prepare the internal data structure containing the passwords */
-       ret = setup_io(ac, ac->req->op.add.message, ac->req->op.add.message, &io);
+       ret = setup_io(ac, ac->req->op.add.message, NULL, &io);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
 
-       ldb = ldb_module_get_ctx(ac->module);
-
-       msg = ldb_msg_copy_shallow(ac, ac->req->op.add.message);
-       if (msg == NULL) {
-               return ldb_operr(ldb);
-       }
-
-       /* remove attributes that we just read into 'io' */
-       ldb_msg_remove_attr(msg, "userPassword");
-       ldb_msg_remove_attr(msg, "clearTextPassword");
-       ldb_msg_remove_attr(msg, "unicodePwd");
-       ldb_msg_remove_attr(msg, "dBCSPwd");
-       ldb_msg_remove_attr(msg, "pwdLastSet");
-
        ret = setup_password_fields(&io);
        if (ret != LDB_SUCCESS) {
                return ret;
@@ -2271,57 +3847,22 @@ static int password_hash_add_do_add(struct ph_context *ac)
                return ret;
        }
 
-       if (io.g.nt_hash) {
-               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(ldb, ac, msg,
-                                        "dBCSPwd", io.g.lm_hash);
-               if (ret != LDB_SUCCESS) {
-                       return ret;
-               }
-       }
-       if (io.g.nt_history_len > 0) {
-               ret = samdb_msg_add_hashes(ldb, ac, msg,
-                                          "ntPwdHistory",
-                                          io.g.nt_history,
-                                          io.g.nt_history_len);
-               if (ret != LDB_SUCCESS) {
-                       return ret;
-               }
-       }
-       if (io.g.lm_history_len > 0) {
-               ret = samdb_msg_add_hashes(ldb, ac, msg,
-                                          "lmPwdHistory",
-                                          io.g.lm_history,
-                                          io.g.lm_history_len);
-               if (ret != LDB_SUCCESS) {
-                       return ret;
-               }
-       }
-       if (io.g.supplemental.length > 0) {
-               ret = ldb_msg_add_value(msg, "supplementalCredentials",
-                                       &io.g.supplemental, NULL);
-               if (ret != LDB_SUCCESS) {
-                       return ret;
-               }
+       ret = setup_smartcard_reset(&io);
+       if (ret != LDB_SUCCESS) {
+               return ret;
        }
-       ret = samdb_msg_add_uint64(ldb, ac, msg,
-                                  "pwdLastSet",
-                                  io.g.last_set);
+
+       ret = update_final_msg(&io);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
 
        ret = ldb_build_add_req(&down_req, ldb, ac,
-                               msg,
+                               ac->update_msg,
                                ac->req->controls,
                                ac, ph_op_callback,
                                ac->req);
+       LDB_REQ_SET_LOCATION(down_req);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
@@ -2331,71 +3872,27 @@ static int password_hash_add_do_add(struct ph_context *ac)
 
 static int password_hash_modify(struct ldb_module *module, struct ldb_request *req)
 {
-       struct ldb_context *ldb;
-       struct ph_context *ac;
+       struct ldb_context *ldb = ldb_module_get_ctx(module);
+       struct ph_context *ac = NULL;
        const char *passwordAttrs[] = { "userPassword", "clearTextPassword",
                "unicodePwd", "dBCSPwd", NULL }, **l;
-       unsigned int attr_cnt, del_attr_cnt, add_attr_cnt, rep_attr_cnt;
+       unsigned int del_attr_cnt, add_attr_cnt, rep_attr_cnt;
        struct ldb_message_element *passwordAttr;
        struct ldb_message *msg;
        struct ldb_request *down_req;
+       struct ldb_control *restore = NULL;
        int ret;
-       struct ldb_control *bypass = NULL;
-
-       ldb = ldb_module_get_ctx(module);
+       unsigned int i = 0;
 
        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, ldb, LOCAL_BASE),
-                               req->op.mod.message->dn) == 0) {
-               return ldb_next_request(module, req);
-       }
-
-       bypass = ldb_request_get_control(req,
-                                        DSDB_CONTROL_BYPASS_PASSWORD_HASH_OID);
-       if (bypass != NULL) {
-               /* Mark the "bypass" control as uncritical (done) */
-               bypass->critical = false;
-               ldb_debug(ldb, LDB_DEBUG_TRACE, "password_hash_modify (bypassing)\n");
-               return ldb_next_request(module, req);
-       }
-
-       /* 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.mod.message, "lmPwdHistory")) {
-               return LDB_ERR_UNWILLING_TO_PERFORM;
-       }
-       if (ldb_msg_find_element(req->op.mod.message, "supplementalCredentials")) {
-               return LDB_ERR_UNWILLING_TO_PERFORM;
-       }
-
-       /* 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);
+       ret = password_hash_needed(module, req, &ac);
+       if (ret != LDB_SUCCESS) {
+               return ret;
        }
-
-       ac = ph_init_context(module, req);
-       if (!ac) {
-               DEBUG(0,(__location__ ": %s\n", ldb_errstring(ldb)));
-               return ldb_operr(ldb);
+       if (ac == NULL) {
+               return ret;
        }
-       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);
@@ -2418,33 +3915,40 @@ static int password_hash_modify(struct ldb_module *module, struct ldb_request *r
        add_attr_cnt = 0;
        rep_attr_cnt = 0;
        for (l = passwordAttrs; *l != NULL; l++) {
+               if ((!ac->userPassword) &&
+                   (ldb_attr_cmp(*l, "userPassword") == 0)) {
+                       continue;
+               }
+
                while ((passwordAttr = ldb_msg_find_element(msg, *l)) != NULL) {
-                       if (passwordAttr->flags == LDB_FLAG_MOD_DELETE) {
+                       if (LDB_FLAG_MOD_TYPE(passwordAttr->flags) == LDB_FLAG_MOD_DELETE) {
                                ++del_attr_cnt;
                        }
-                       if (passwordAttr->flags == LDB_FLAG_MOD_ADD) {
+                       if (LDB_FLAG_MOD_TYPE(passwordAttr->flags) == LDB_FLAG_MOD_ADD) {
                                ++add_attr_cnt;
                        }
-                       if (passwordAttr->flags == LDB_FLAG_MOD_REPLACE) {
+                       if (LDB_FLAG_MOD_TYPE(passwordAttr->flags) == LDB_FLAG_MOD_REPLACE) {
                                ++rep_attr_cnt;
                        }
                        if ((passwordAttr->num_values != 1) &&
-                           (passwordAttr->flags != LDB_FLAG_MOD_REPLACE)) {
+                           (LDB_FLAG_MOD_TYPE(passwordAttr->flags) == LDB_FLAG_MOD_ADD)) {
+                               talloc_free(ac);
+                               ldb_asprintf_errstring(ldb,
+                                                      "'%s' attribute must have exactly one value on add operations!",
+                                                      *l);
+                               return LDB_ERR_CONSTRAINT_VIOLATION;
+                       }
+                       if ((passwordAttr->num_values > 1) &&
+                           (LDB_FLAG_MOD_TYPE(passwordAttr->flags) == LDB_FLAG_MOD_DELETE)) {
                                talloc_free(ac);
                                ldb_asprintf_errstring(ldb,
-                                                      "'%s' attributes must have exactly one value!",
+                                                      "'%s' attribute must have zero or one value(s) on delete operations!",
                                                       *l);
                                return LDB_ERR_CONSTRAINT_VIOLATION;
                        }
                        ldb_msg_remove_element(msg, passwordAttr);
                }
        }
-       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;
-       }
        if ((del_attr_cnt == 0) && (add_attr_cnt > 0)) {
                talloc_free(ac);
                ldb_set_errstring(ldb,
@@ -2464,16 +3968,41 @@ static int password_hash_modify(struct ldb_module *module, struct ldb_request *r
                return LDB_ERR_UNWILLING_TO_PERFORM;
        }
 
+       restore = ldb_request_get_control(req,
+                                       DSDB_CONTROL_RESTORE_TOMBSTONE_OID);
+       if (restore == NULL) {
+               /*
+                * A tomstone reanimation generates a double update
+                * of pwdLastSet.
+                *
+                * So we only remove it without the
+                * DSDB_CONTROL_RESTORE_TOMBSTONE_OID control.
+                */
+               ldb_msg_remove_attr(msg, "pwdLastSet");
+       }
+
+
        /* if there was nothing else to be modified skip to next step */
        if (msg->num_elements == 0) {
                return password_hash_mod_search_self(ac);
        }
 
+       /*
+        * Now we apply all changes remaining in msg
+        * and remove them from our final update_msg
+        */
+
+       for (i = 0; i < msg->num_elements; i++) {
+               ldb_msg_remove_attr(ac->update_msg,
+                                   msg->elements[i].name);
+       }
+
        ret = ldb_build_mod_req(&down_req, ldb, ac,
                                msg,
                                req->controls,
                                ac, ph_modify_callback,
                                req);
+       LDB_REQ_SET_LOCATION(down_req);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
@@ -2516,7 +4045,7 @@ static int ph_mod_search_callback(struct ldb_request *req, struct ldb_reply *are
 {
        struct ldb_context *ldb;
        struct ph_context *ac;
-       int ret;
+       int ret = LDB_SUCCESS;
 
        ac = talloc_get_type(req->context, struct ph_context);
        ldb = ldb_module_get_ctx(ac->module);
@@ -2596,6 +4125,7 @@ static int password_hash_mod_search_self(struct ph_context *ac)
        struct ldb_context *ldb;
        static const char * const attrs[] = { "objectClass",
                                              "userAccountControl",
+                                             "msDS-User-Account-Control-Computed",
                                              "pwdLastSet",
                                              "sAMAccountName",
                                              "objectSid",
@@ -2605,6 +4135,10 @@ static int password_hash_mod_search_self(struct ph_context *ac)
                                              "ntPwdHistory",
                                              "dBCSPwd",
                                              "unicodePwd",
+                                             "badPasswordTime",
+                                             "badPwdCount",
+                                             "lockoutTime",
+                                             "msDS-SecondaryKrbTgtNumber",
                                              NULL };
        struct ldb_request *search_req;
        int ret;
@@ -2619,7 +4153,7 @@ static int password_hash_mod_search_self(struct ph_context *ac)
                                   NULL,
                                   ac, ph_mod_search_callback,
                                   ac->req);
-
+       LDB_REQ_SET_LOCATION(search_req);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
@@ -2630,46 +4164,16 @@ static int password_hash_mod_search_self(struct ph_context *ac)
 static int password_hash_mod_do_mod(struct ph_context *ac)
 {
        struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
-       struct loadparm_context *lp_ctx =
-               lp_ctx = talloc_get_type(ldb_get_opaque(ldb, "loadparm"),
-                                        struct loadparm_context);
        struct ldb_request *mod_req;
-       struct ldb_message *msg;
-       const struct ldb_message *orig_msg, *searched_msg;
        struct setup_password_fields_io io;
        int ret;
-       NTSTATUS status;
-
-       /* use a new message structure so that we can modify it */
-       msg = ldb_msg_new(ac);
-       if (msg == NULL) {
-               return ldb_operr(ldb);
-       }
-
-       /* modify dn */
-       msg->dn = ac->req->op.mod.message->dn;
-
-       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);
+       ret = setup_io(ac, ac->req->op.mod.message,
+                      ac->search_res->message, &io);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
-       
-       /* Get the old password from the database */
-       status = samdb_result_passwords(io.ac,
-                                       lp_ctx,
-                                       discard_const_p(struct ldb_message, searched_msg),
-                                       &io.o.lm_hash, &io.o.nt_hash);
-       if (!NT_STATUS_IS_OK(status)) {
-               return ldb_operr(ldb);
-       }
-
-       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");
 
        ret = setup_password_fields(&io);
        if (ret != LDB_SUCCESS) {
@@ -2681,65 +4185,22 @@ static int password_hash_mod_do_mod(struct ph_context *ac)
                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);
-       ret = ldb_msg_add_empty(msg, "ntPwdHistory", LDB_FLAG_MOD_REPLACE, NULL);
-       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);
-
-       if (io.g.nt_hash) {
-               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(ldb, ac, msg,
-                                        "dBCSPwd", io.g.lm_hash);
-               if (ret != LDB_SUCCESS) {
-                       return ret;
-               }
-       }
-       if (io.g.nt_history_len > 0) {
-               ret = samdb_msg_add_hashes(ldb, ac, msg,
-                                          "ntPwdHistory",
-                                          io.g.nt_history,
-                                          io.g.nt_history_len);
-               if (ret != LDB_SUCCESS) {
-                       return ret;
-               }
-       }
-       if (io.g.lm_history_len > 0) {
-               ret = samdb_msg_add_hashes(ldb, ac, msg,
-                                          "lmPwdHistory",
-                                          io.g.lm_history,
-                                          io.g.lm_history_len);
-               if (ret != LDB_SUCCESS) {
-                       return ret;
-               }
-       }
-       if (io.g.supplemental.length > 0) {
-               ret = ldb_msg_add_value(msg, "supplementalCredentials",
-                                       &io.g.supplemental, NULL);
-               if (ret != LDB_SUCCESS) {
-                       return ret;
-               }
+       ret = setup_smartcard_reset(&io);
+       if (ret != LDB_SUCCESS) {
+               return ret;
        }
-       ret = samdb_msg_add_uint64(ldb, ac, msg,
-                                  "pwdLastSet",
-                                  io.g.last_set);
+
+       ret = update_final_msg(&io);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
 
        ret = ldb_build_mod_req(&mod_req, ldb, ac,
-                               msg,
+                               ac->update_msg,
                                ac->req->controls,
                                ac, ph_op_callback,
                                ac->req);
+       LDB_REQ_SET_LOCATION(mod_req);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
@@ -2747,8 +4208,36 @@ static int password_hash_mod_do_mod(struct ph_context *ac)
        return ldb_next_request(ac->module, mod_req);
 }
 
-_PUBLIC_ const struct ldb_module_ops ldb_password_hash_module_ops = {
+static const struct ldb_module_ops ldb_password_hash_module_ops = {
        .name          = "password_hash",
        .add           = password_hash_add,
        .modify        = password_hash_modify
 };
+
+int ldb_password_hash_module_init(const char *version)
+{
+#ifdef ENABLE_GPGME
+       const char *gversion = NULL;
+#endif /* ENABLE_GPGME */
+
+       LDB_MODULE_CHECK_VERSION(version);
+
+#ifdef ENABLE_GPGME
+       /*
+        * Note: this sets a SIGPIPE handler
+        * if none is active already. See:
+        * https://www.gnupg.org/documentation/manuals/gpgme/Signal-Handling.html#Signal-Handling
+        */
+       gversion = gpgme_check_version(GPGME_VERSION);
+       if (gversion == NULL) {
+               fprintf(stderr, "%s() in %s version[%s]: "
+                       "gpgme_check_version(%s) not available, "
+                       "gpgme_check_version(NULL) => '%s'\n",
+                       __func__, __FILE__, version,
+                       GPGME_VERSION, gpgme_check_version(NULL));
+               return LDB_ERR_UNAVAILABLE;
+       }
+#endif /* ENABLE_GPGME */
+
+       return ldb_register_module(&ldb_password_hash_module_ops);
+}