s4-dsdb: pass parent request to dsdb_module_*() functions
[samba.git] / source4 / dsdb / samdb / ldb_modules / password_hash.c
index 3433fdbe1740e6161fb682d9b4902ae817d47383..ea51001365267a4c5ef1990ae769b0e9c781ea28 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 "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"
@@ -95,12 +89,12 @@ struct ph_context {
        struct ldb_reply *search_res;
 
        struct dsdb_control_password_change_status *status;
+       struct dsdb_control_password_change *change;
 
        bool pwd_reset;
-
        bool change_status;
        bool hash_values;
-       bool change_old_pw_checked;
+       bool userPassword;
 };
 
 
@@ -116,6 +110,7 @@ struct setup_password_fields_io {
                const char *sAMAccountName;
                const char *user_principal_name;
                bool is_computer;
+               uint32_t restrictions;
        } u;
 
        /* new credentials and old given credentials */
@@ -156,6 +151,399 @@ struct setup_password_fields_io {
        } g;
 };
 
+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) {
+                       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 */
 
@@ -176,8 +564,7 @@ static int setup_nt_fields(struct setup_password_fields_io *io)
                                        struct samr_Password,
                                        io->ac->status->domain_data.pwdHistoryLength);
        if (!io->g.nt_history) {
-               ldb_oom(ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
+               return ldb_oom(ldb);
        }
 
        for (i = 0; i < MIN(io->ac->status->domain_data.pwdHistoryLength-1,
@@ -214,13 +601,12 @@ static int setup_lm_fields(struct setup_password_fields_io *io)
                return LDB_SUCCESS;
        }
 
-       /* We might not have an old NT password */
+       /* We might not have an old LM password */
        io->g.lm_history = talloc_array(io->ac,
                                        struct samr_Password,
                                        io->ac->status->domain_data.pwdHistoryLength);
        if (!io->g.lm_history) {
-               ldb_oom(ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
+               return ldb_oom(ldb);
        }
 
        for (i = 0; i < MIN(io->ac->status->domain_data.pwdHistoryLength-1,
@@ -264,8 +650,7 @@ static int setup_kerberos_keys(struct setup_password_fields_io *io)
 
                name = strlower_talloc(io->ac, io->u.sAMAccountName);
                if (!name) {
-                       ldb_oom(ldb);
-                       return LDB_ERR_OPERATIONS_ERROR;
+                       return ldb_oom(ldb);
                }
 
                if (name[strlen(name)-1] == '$') {
@@ -275,8 +660,7 @@ static int setup_kerberos_keys(struct setup_password_fields_io *io)
                saltbody = talloc_asprintf(io->ac, "%s.%s", name,
                                           io->ac->status->domain_data.dns_domain);
                if (!saltbody) {
-                       ldb_oom(ldb);
-                       return LDB_ERR_OPERATIONS_ERROR;
+                       return ldb_oom(ldb);
                }
                
                krb5_ret = krb5_make_principal(io->smb_krb5_context->krb5_context,
@@ -289,8 +673,7 @@ static int setup_kerberos_keys(struct setup_password_fields_io *io)
 
                user_principal_name = talloc_strdup(io->ac, io->u.user_principal_name);
                if (!user_principal_name) {
-                       ldb_oom(ldb);
-                       return LDB_ERR_OPERATIONS_ERROR;
+                       return ldb_oom(ldb);
                }
 
                p = strchr(user_principal_name, '@');
@@ -337,8 +720,7 @@ static int setup_kerberos_keys(struct setup_password_fields_io *io)
                                    salt.saltvalue.length);
        krb5_free_salt(io->smb_krb5_context->krb5_context, salt);
        if (!io->g.salt) {
-               ldb_oom(ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
+               return ldb_oom(ldb);
        }
        salt.saltvalue.data     = discard_const(io->g.salt);
        salt.saltvalue.length   = strlen(io->g.salt);
@@ -365,8 +747,7 @@ static int setup_kerberos_keys(struct setup_password_fields_io *io)
                                         key.keyvalue.length);
        krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
        if (!io->g.aes_256.data) {
-               ldb_oom(ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
+               return ldb_oom(ldb);
        }
 
        /*
@@ -391,8 +772,7 @@ static int setup_kerberos_keys(struct setup_password_fields_io *io)
                                         key.keyvalue.length);
        krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
        if (!io->g.aes_128.data) {
-               ldb_oom(ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
+               return ldb_oom(ldb);
        }
 
        /*
@@ -417,8 +797,7 @@ static int setup_kerberos_keys(struct setup_password_fields_io *io)
                                         key.keyvalue.length);
        krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
        if (!io->g.des_md5.data) {
-               ldb_oom(ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
+               return ldb_oom(ldb);
        }
 
        /*
@@ -443,8 +822,7 @@ static int setup_kerberos_keys(struct setup_password_fields_io *io)
                                         key.keyvalue.length);
        krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
        if (!io->g.des_crc.data) {
-               ldb_oom(ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
+               return ldb_oom(ldb);
        }
 
        return LDB_SUCCESS;
@@ -477,8 +855,7 @@ static int setup_primary_kerberos(struct setup_password_fields_io *io,
                                               struct package_PrimaryKerberosKey3,
                                               pkb3->num_keys);
        if (!pkb3->keys) {
-               ldb_oom(ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
+               return ldb_oom(ldb);
        }
 
        pkb3->keys[0].keytype   = ENCTYPE_DES_CBC_MD5;
@@ -513,12 +890,11 @@ static int setup_primary_kerberos(struct setup_password_fields_io *io,
 
                blob = strhex_to_data_blob(io->ac, old_scp->data);
                if (!blob.data) {
-                       ldb_oom(ldb);
-                       return LDB_ERR_OPERATIONS_ERROR;
+                       return ldb_oom(ldb);
                }
 
                /* TODO: use ndr_pull_struct_blob_all(), when the ndr layer handles it correct with relative pointers */
-               ndr_err = ndr_pull_struct_blob(&blob, io->ac, lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")), &_old_pkb,
+               ndr_err = ndr_pull_struct_blob(&blob, io->ac, &_old_pkb,
                                               (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
                if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
                        NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
@@ -583,8 +959,7 @@ static int setup_primary_kerberos_newer(struct setup_password_fields_io *io,
                                  struct package_PrimaryKerberosKey4,
                                  pkb4->num_keys);
        if (!pkb4->keys) {
-               ldb_oom(ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
+               return ldb_oom(ldb);
        }
 
        pkb4->keys[0].iteration_count   = 4096;
@@ -629,13 +1004,11 @@ static int setup_primary_kerberos_newer(struct setup_password_fields_io *io,
 
                blob = strhex_to_data_blob(io->ac, old_scp->data);
                if (!blob.data) {
-                       ldb_oom(ldb);
-                       return LDB_ERR_OPERATIONS_ERROR;
+                       return ldb_oom(ldb);
                }
 
                /* TODO: use ndr_pull_struct_blob_all(), when the ndr layer handles it correct with relative pointers */
                ndr_err = ndr_pull_struct_blob(&blob, io->ac,
-                                              lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")),
                                               &_old_pkb,
                                               (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
                if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
@@ -923,13 +1296,11 @@ static int setup_primary_wdigest(struct setup_password_fields_io *io,
        sAMAccountName          = data_blob_string_const(io->u.sAMAccountName);
        sAMAccountName_l        = data_blob_string_const(strlower_talloc(io->ac, io->u.sAMAccountName));
        if (!sAMAccountName_l.data) {
-               ldb_oom(ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
+               return ldb_oom(ldb);
        }
        sAMAccountName_u        = data_blob_string_const(strupper_talloc(io->ac, io->u.sAMAccountName));
        if (!sAMAccountName_u.data) {
-               ldb_oom(ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
+               return ldb_oom(ldb);
        }
 
        /* if the user doesn't have a userPrincipalName, create one (with lower case realm) */
@@ -938,34 +1309,29 @@ static int setup_primary_wdigest(struct setup_password_fields_io *io,
                                                      io->u.sAMAccountName,
                                                      io->ac->status->domain_data.dns_domain);
                if (!user_principal_name) {
-                       ldb_oom(ldb);
-                       return LDB_ERR_OPERATIONS_ERROR;
+                       return ldb_oom(ldb);
                }       
        }
        userPrincipalName       = data_blob_string_const(user_principal_name);
        userPrincipalName_l     = data_blob_string_const(strlower_talloc(io->ac, user_principal_name));
        if (!userPrincipalName_l.data) {
-               ldb_oom(ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
+               return ldb_oom(ldb);
        }
        userPrincipalName_u     = data_blob_string_const(strupper_talloc(io->ac, user_principal_name));
        if (!userPrincipalName_u.data) {
-               ldb_oom(ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
+               return ldb_oom(ldb);
        }
 
        netbios_domain          = data_blob_string_const(io->ac->status->domain_data.netbios_domain);
        netbios_domain_l        = data_blob_string_const(strlower_talloc(io->ac,
                                                                         io->ac->status->domain_data.netbios_domain));
        if (!netbios_domain_l.data) {
-               ldb_oom(ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
+               return ldb_oom(ldb);
        }
        netbios_domain_u        = data_blob_string_const(strupper_talloc(io->ac,
                                                                         io->ac->status->domain_data.netbios_domain));
        if (!netbios_domain_u.data) {
-               ldb_oom(ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
+               return ldb_oom(ldb);
        }
 
        dns_domain              = data_blob_string_const(io->ac->status->domain_data.dns_domain);
@@ -981,8 +1347,7 @@ static int setup_primary_wdigest(struct setup_password_fields_io *io,
        pdb->hashes     = talloc_array(io->ac, struct package_PrimaryWDigestHash,
                                       pdb->num_hashes);
        if (!pdb->hashes) {
-               ldb_oom(ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
+               return ldb_oom(ldb);
        }
 
        for (i=0; i < ARRAY_SIZE(wdigest); i++) {
@@ -1067,7 +1432,6 @@ static int setup_supplemental_field(struct setup_password_fields_io *io)
        /* if there's an old supplementaCredentials blob then parse it */
        if (io->o.supplemental) {
                ndr_err = ndr_pull_struct_blob_all(io->o.supplemental, io->ac,
-                                                  lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")),
                                                   &_old_scb,
                                                   (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
                if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
@@ -1147,7 +1511,6 @@ static int setup_supplemental_field(struct setup_password_fields_io *io)
                }
 
                ndr_err = ndr_push_struct_blob(&pknb_blob, io->ac,
-                                              lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")),
                                               &pknb,
                                               (ndr_push_flags_fn_t)ndr_push_package_PrimaryKerberosBlob);
                if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
@@ -1160,8 +1523,7 @@ static int setup_supplemental_field(struct setup_password_fields_io *io)
                }
                pknb_hexstr = data_blob_hex_string_upper(io->ac, &pknb_blob);
                if (!pknb_hexstr) {
-                       ldb_oom(ldb);
-                       return LDB_ERR_OPERATIONS_ERROR;
+                       return ldb_oom(ldb);
                }
                pkn->name       = "Primary:Kerberos-Newer-Keys";
                pkn->reserved   = 1;
@@ -1179,7 +1541,6 @@ static int setup_supplemental_field(struct setup_password_fields_io *io)
        }
 
        ndr_err = ndr_push_struct_blob(&pkb_blob, io->ac, 
-                                      lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")),
                                       &pkb,
                                       (ndr_push_flags_fn_t)ndr_push_package_PrimaryKerberosBlob);
        if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
@@ -1192,8 +1553,7 @@ static int setup_supplemental_field(struct setup_password_fields_io *io)
        }
        pkb_hexstr = data_blob_hex_string_upper(io->ac, &pkb_blob);
        if (!pkb_hexstr) {
-               ldb_oom(ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
+               return ldb_oom(ldb);
        }
        pk->name        = "Primary:Kerberos";
        pk->reserved    = 1;
@@ -1210,7 +1570,6 @@ static int setup_supplemental_field(struct setup_password_fields_io *io)
        }
 
        ndr_err = ndr_push_struct_blob(&pdb_blob, io->ac, 
-                                      lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")),
                                       &pdb,
                                       (ndr_push_flags_fn_t)ndr_push_package_PrimaryWDigestBlob);
        if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
@@ -1223,8 +1582,7 @@ static int setup_supplemental_field(struct setup_password_fields_io *io)
        }
        pdb_hexstr = data_blob_hex_string_upper(io->ac, &pdb_blob);
        if (!pdb_hexstr) {
-               ldb_oom(ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
+               return ldb_oom(ldb);
        }
        pd->name        = "Primary:WDigest";
        pd->reserved    = 1;
@@ -1239,7 +1597,6 @@ static int setup_supplemental_field(struct setup_password_fields_io *io)
                pcb.cleartext   = *io->n.cleartext_utf16;
 
                ndr_err = ndr_push_struct_blob(&pcb_blob, io->ac, 
-                                              lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")),
                                               &pcb,
                                               (ndr_push_flags_fn_t)ndr_push_package_PrimaryCLEARTEXTBlob);
                if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
@@ -1252,8 +1609,7 @@ static int setup_supplemental_field(struct setup_password_fields_io *io)
                }
                pcb_hexstr = data_blob_hex_string_upper(io->ac, &pcb_blob);
                if (!pcb_hexstr) {
-                       ldb_oom(ldb);
-                       return LDB_ERR_OPERATIONS_ERROR;
+                       return ldb_oom(ldb);
                }
                pc->name        = "Primary:CLEARTEXT";
                pc->reserved    = 1;
@@ -1265,7 +1621,6 @@ static int setup_supplemental_field(struct setup_password_fields_io *io)
         */
        pb.names = names;
        ndr_err = ndr_push_struct_blob(&pb_blob, io->ac, 
-                                      lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")), 
                                       &pb,
                                       (ndr_push_flags_fn_t)ndr_push_package_PackagesBlob);
        if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
@@ -1278,8 +1633,7 @@ static int setup_supplemental_field(struct setup_password_fields_io *io)
        }
        pb_hexstr = data_blob_hex_string_upper(io->ac, &pb_blob);
        if (!pb_hexstr) {
-               ldb_oom(ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
+               return ldb_oom(ldb);
        }
        pp->name        = "Packages";
        pp->reserved    = 2;
@@ -1293,7 +1647,6 @@ static int setup_supplemental_field(struct setup_password_fields_io *io)
        scb.sub.packages        = packages;
 
        ndr_err = ndr_push_struct_blob(&io->g.supplemental, io->ac, 
-                                      lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")),
                                       &scb,
                                       (ndr_push_flags_fn_t)ndr_push_supplementalCredentialsBlob);
        if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
@@ -1325,54 +1678,63 @@ 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) {
-                       ldb_oom(ldb);
-                       return LDB_ERR_OPERATIONS_ERROR;
+                       return ldb_oom(ldb);
                }
-               if (!convert_string_talloc_convenience(io->ac,
-                                                      lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")),
-                                                      CH_UTF8, CH_UTF16,
-                                                      g->cleartext_utf8->data,
-                                                      g->cleartext_utf8->length,
-                                                      (void *)&cleartext_utf16_str,
-                                                      &converted_pw_len, false)) {
-                       ldb_asprintf_errstring(ldb,
-                               "setup_password_fields: "
-                               "failed to generate UTF16 password from cleartext UTF8 password");
-                       return LDB_ERR_OPERATIONS_ERROR;
+               if (!convert_string_talloc(io->ac,
+                                          CH_UTF8, CH_UTF16,
+                                          g->cleartext_utf8->data,
+                                          g->cleartext_utf8->length,
+                                          (void *)&cleartext_utf16_blob->data,
+                                          &cleartext_utf16_blob->length,
+                                          false)) {
+                       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) {
-                       ldb_oom(ldb);
-                       return LDB_ERR_OPERATIONS_ERROR;
+                       return ldb_oom(ldb);
                }
-               if (!convert_string_talloc_convenience(io->ac,
-                                                      lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")),
-                                                      CH_UTF16MUNGED, CH_UTF8,
-                                                      g->cleartext_utf16->data,
-                                                      g->cleartext_utf16->length,
-                                                      (void *)&cleartext_utf8_str,
-                                                      &converted_pw_len, false)) {
-                       /* We can't bail out entirely, as these unconvertable passwords are frustratingly valid */
-                       talloc_free(cleartext_utf8_blob);
-               } else {
-                       *cleartext_utf8_blob = data_blob_const(cleartext_utf8_str,
-                                                              converted_pw_len);
-                       g->cleartext_utf8 = cleartext_utf8_blob;
+               if (!convert_string_talloc(io->ac,
+                                          CH_UTF16MUNGED, CH_UTF8,
+                                          g->cleartext_utf16->data,
+                                          g->cleartext_utf16->length,
+                                          (void *)&cleartext_utf8_blob->data,
+                                          &cleartext_utf8_blob->length,
+                                          false)) {
+                       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,8 +1742,7 @@ static int setup_given_passwords(struct setup_password_fields_io *io,
 
                nt_hash = talloc(io->ac, struct samr_Password);
                if (!nt_hash) {
-                       ldb_oom(ldb);
-                       return LDB_ERR_OPERATIONS_ERROR;
+                       return ldb_oom(ldb);
                }
                g->nt_hash = nt_hash;
 
@@ -1391,14 +1752,12 @@ static int setup_given_passwords(struct setup_password_fields_io *io,
                       g->cleartext_utf16->length);
        }
 
-       if (g->cleartext_utf8 &&
-           lp_lanman_auth(ldb_get_opaque(ldb, "loadparm"))) {
+       if (g->cleartext_utf8) {
                struct samr_Password *lm_hash;
 
                lm_hash = talloc(io->ac, struct samr_Password);
                if (!lm_hash) {
-                       ldb_oom(ldb);
-                       return LDB_ERR_OPERATIONS_ERROR;
+                       return ldb_oom(ldb);
                }
 
                /* compute the new lm hash */
@@ -1415,11 +1774,12 @@ static int setup_given_passwords(struct setup_password_fields_io *io,
 
 static int setup_password_fields(struct setup_password_fields_io *io)
 {
-       struct ldb_context *ldb;
+       struct ldb_context *ldb = ldb_module_get_ctx(io->ac->module);
+       struct loadparm_context *lp_ctx =
+               lp_ctx = talloc_get_type(ldb_get_opaque(ldb, "loadparm"),
+                                        struct loadparm_context);
        int ret;
 
-       ldb = ldb_module_get_ctx(io->ac->module);
-
        /* transform the old password (for password changes) */
        ret = setup_given_passwords(io, &io->og);
        if (ret != LDB_SUCCESS) {
@@ -1444,9 +1804,14 @@ static int setup_password_fields(struct setup_password_fields_io *io)
                return ret;
        }
 
-       ret = setup_lm_fields(io);
-       if (ret != LDB_SUCCESS) {
-               return ret;
+       if (lpcfg_lanman_auth(lp_ctx)) {
+               ret = setup_lm_fields(io);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
+               }
+       } else {
+               io->g.lm_hash = NULL;
+               io->g.lm_history_len = 0;
        }
 
        ret = setup_supplemental_field(io);
@@ -1462,6 +1827,274 @@ static int setup_password_fields(struct setup_password_fields_io *io)
        return LDB_SUCCESS;
 }
 
+static int check_password_restrictions(struct setup_password_fields_io *io)
+{
+       struct ldb_context *ldb;
+       int ret;
+       enum samr_ValidationStatus stat;
+
+       ldb = ldb_module_get_ctx(io->ac->module);
+
+       /* First check the old password is correct, for password changes */
+       if (!io->ac->pwd_reset) {
+               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 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) {
+                               ret = LDB_ERR_CONSTRAINT_VIOLATION;
+                               ldb_asprintf_errstring(ldb,
+                                       "%08X: %s - check_password_restrictions: "
+                                       "There's no old nt_hash, which is needed "
+                                       "in order to change your password!",
+                                       W_ERROR_V(WERR_INVALID_PASSWORD),
+                                       ldb_strerror(ret));
+                               return ret;
+                       }
+
+                       if (memcmp(io->og.nt_hash->hash, io->o.nt_hash->hash, 16) != 0) {
+                               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;
+                       }
+
+                       nt_hash_checked = true;
+               }
+
+               /* 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) {
+                               ret = LDB_ERR_CONSTRAINT_VIOLATION;
+                               ldb_asprintf_errstring(ldb,
+                                       "%08X: %s - check_password_restrictions: "
+                                       "There's no old lm_hash, which is needed "
+                                       "in order to change your password!",
+                                       W_ERROR_V(WERR_INVALID_PASSWORD),
+                                       ldb_strerror(ret));
+                               return ret;
+                       }
+
+                       if (io->o.lm_hash &&
+                           memcmp(io->og.lm_hash->hash, io->o.lm_hash->hash, 16) != 0) {
+                               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;
+                       }
+               }
+       }
+
+       if (io->u.restrictions == 0) {
+               /* FIXME: Is this right? */
+               return LDB_SUCCESS;
+       }
+
+       /*
+        * Fundamental password checks done by the call
+        * "samdb_check_password".
+        * It is also in use by "dcesrv_samr_ValidatePassword".
+        */
+       if (io->n.cleartext_utf8 != NULL) {
+               stat = samdb_check_password(io->n.cleartext_utf8,
+                                           io->ac->status->domain_data.pwdProperties,
+                                           io->ac->status->domain_data.minPwdLength);
+               switch (stat) {
+               case SAMR_VALIDATION_STATUS_SUCCESS:
+                               /* perfect -> proceed! */
+                       break;
+
+               case SAMR_VALIDATION_STATUS_PWD_TOO_SHORT:
+                       ret = LDB_ERR_CONSTRAINT_VIOLATION;
+                       ldb_asprintf_errstring(ldb,
+                               "%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 ret;
+
+               case SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH:
+                       ret = LDB_ERR_CONSTRAINT_VIOLATION;
+                       ldb_asprintf_errstring(ldb,
+                               "%08X: %s - check_password_restrictions: "
+                               "the password does not meet the complexity criterias!",
+                               W_ERROR_V(WERR_PASSWORD_RESTRICTION),
+                               ldb_strerror(ret));
+                       io->ac->status->reject_reason = SAM_PWD_CHANGE_NOT_COMPLEX;
+                       return ret;
+
+               default:
+                       ret = LDB_ERR_CONSTRAINT_VIOLATION;
+                       ldb_asprintf_errstring(ldb,
+                               "%08X: %s - check_password_restrictions: "
+                               "the password doesn't fit by a certain reason!",
+                               W_ERROR_V(WERR_PASSWORD_RESTRICTION),
+                               ldb_strerror(ret));
+                       return ret;
+               }
+       }
+
+       if (io->ac->pwd_reset) {
+               return LDB_SUCCESS;
+       }
+
+       if (io->n.nt_hash) {
+               uint32_t i;
+
+               /* checks the NT hash password history */
+               for (i = 0; i < io->o.nt_history_len; i++) {
+                       ret = memcmp(io->n.nt_hash, io->o.nt_history[i].hash, 16);
+                       if (ret == 0) {
+                               ret = LDB_ERR_CONSTRAINT_VIOLATION;
+                               ldb_asprintf_errstring(ldb,
+                                       "%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 ret;
+                       }
+               }
+       }
+
+       if (io->n.lm_hash) {
+               uint32_t i;
+
+               /* checks the LM hash password history */
+               for (i = 0; i < io->o.lm_history_len; i++) {
+                       ret = memcmp(io->n.nt_hash, io->o.lm_history[i].hash, 16);
+                       if (ret == 0) {
+                               ret = LDB_ERR_CONSTRAINT_VIOLATION;
+                               ldb_asprintf_errstring(ldb,
+                                       "%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 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,
+                       "%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,
+                       "%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) {
+               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;
+       }
+
+       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, 
@@ -1469,6 +2102,9 @@ static int setup_io(struct ph_context *ac,
 { 
        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);
        int ret;
 
        ZERO_STRUCTP(io);
@@ -1479,15 +2115,18 @@ static int setup_io(struct ph_context *ac,
                                  ldb_get_event_context(ldb),
                                  (struct loadparm_context *)ldb_get_opaque(ldb, "loadparm"),
                                  &io->smb_krb5_context) != 0) {
-               return LDB_ERR_OPERATIONS_ERROR;
+               return ldb_operr(ldb);
        }
 
        io->ac                          = ac;
 
-       io->u.userAccountControl        = samdb_result_uint(searched_msg, "userAccountControl", 0);
+       io->u.userAccountControl        = ldb_msg_find_attr_as_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.sAMAccountName            = ldb_msg_find_attr_as_string(searched_msg,
+                                                                     "sAMAccountName", NULL);
+       io->u.user_principal_name       = ldb_msg_find_attr_as_string(searched_msg,
+                                                                     "userPrincipalName", NULL);
        io->u.is_computer               = ldb_msg_check_string_attribute(searched_msg, "objectClass", "computer");
 
        if (io->u.sAMAccountName == NULL) {
@@ -1498,17 +2137,34 @@ static int setup_io(struct ph_context *ac,
                return LDB_ERR_CONSTRAINT_VIOLATION;
        }
 
-       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;
+       /* Only non-trust accounts have restrictions (possibly this test is the
+        * wrong way around, but we like to be restrictive if possible */
+       io->u.restrictions = !(io->u.userAccountControl
+               & (UF_INTERDOMAIN_TRUST_ACCOUNT | UF_WORKSTATION_TRUST_ACCOUNT
+                       | UF_SERVER_TRUST_ACCOUNT));
+
+       if ((io->u.userAccountControl & UF_PASSWD_NOTREQD) != 0) {
+               /* see [MS-ADTS] 2.2.15 */
+               io->u.restrictions = 0;
        }
 
-       ret = samdb_msg_find_old_and_new_ldb_val(orig_msg, "clearTextPassword",
-               &io->n.cleartext_utf16, &io->og.cleartext_utf16);
+       if (ac->userPassword) {
+               ret = msg_find_old_and_new_pwd_val(orig_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;
+               }
+       }
+
+       ret = msg_find_old_and_new_pwd_val(orig_msg, "clearTextPassword",
+                                          ac->req->operation,
+                                          &io->n.cleartext_utf16,
+                                          &io->og.cleartext_utf16);
        if (ret != LDB_SUCCESS) {
                ldb_asprintf_errstring(ldb,
                        "setup_io: "
@@ -1529,8 +2185,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(orig_msg, "unicodePwd",
+                                          ac->req->operation,
+                                          &quoted_utf16,
+                                          &old_quoted_utf16);
        if (ret != LDB_SUCCESS) {
                ldb_asprintf_errstring(ldb,
                        "setup_io: "
@@ -1562,8 +2220,7 @@ static int setup_io(struct ph_context *ac,
                 */
                quoted_utf16_2 = talloc(io->ac, struct ldb_val);
                if (quoted_utf16_2 == NULL) {
-                       ldb_oom(ldb);
-                       return LDB_ERR_OPERATIONS_ERROR;
+                       return ldb_oom(ldb);
                }
 
                quoted_utf16_2->data = quoted_utf16->data + 2;
@@ -1571,7 +2228,7 @@ static int setup_io(struct ph_context *ac,
                io->n.cleartext_utf16 = quoted_utf16_2;
                io->n.nt_hash = NULL;
 
-       } else {
+       } else if (quoted_utf16) {
                /* We have only the hash available -> so no plaintext here */
                if (!ac->hash_values) {
                        /* refuse the change if someone wants to change
@@ -1619,8 +2276,7 @@ static int setup_io(struct ph_context *ac,
                 */
                old_quoted_utf16_2 = talloc(io->ac, struct ldb_val);
                if (old_quoted_utf16_2 == NULL) {
-                       ldb_oom(ldb);
-                       return LDB_ERR_OPERATIONS_ERROR;
+                       return ldb_oom(ldb);
                }
 
                old_quoted_utf16_2->data = old_quoted_utf16->data + 2;
@@ -1628,7 +2284,7 @@ static int setup_io(struct ph_context *ac,
 
                io->og.cleartext_utf16 = old_quoted_utf16_2;
                io->og.nt_hash = NULL;
-       } else {
+       } else if (old_quoted_utf16) {
                /* We have only the hash available -> so no plaintext here */
                if (!ac->hash_values) {
                        /* refuse the change if someone wants to change
@@ -1646,8 +2302,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(orig_msg, "dBCSPwd",
+                                          ac->req->operation,
+                                          &lm_hash, &old_lm_hash);
        if (ret != LDB_SUCCESS) {
                ldb_asprintf_errstring(ldb,
                        "setup_io: "
@@ -1663,18 +2320,39 @@ static int setup_io(struct ph_context *ac,
                        "it's not allowed to set the LM hash password directly'");
                return LDB_ERR_UNWILLING_TO_PERFORM;
        }
-       if (lm_hash != NULL) {
+
+       if (lpcfg_lanman_auth(lp_ctx) && (lm_hash != NULL)) {
                io->n.lm_hash = talloc(io->ac, struct samr_Password);
                memcpy(io->n.lm_hash->hash, lm_hash->data, MIN(lm_hash->length,
                       sizeof(io->n.lm_hash->hash)));
        }
-
-       if (old_lm_hash != NULL) {
+       if (lpcfg_lanman_auth(lp_ctx) && (old_lm_hash != NULL)) {
                io->og.lm_hash = talloc(io->ac, struct samr_Password);
                memcpy(io->og.lm_hash->hash, old_lm_hash->data, MIN(old_lm_hash->length,
                       sizeof(io->og.lm_hash->hash)));
        }
 
+       /*
+        * 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)
@@ -1694,6 +2372,23 @@ static int setup_io(struct ph_context *ac,
                return LDB_ERR_UNWILLING_TO_PERFORM;
        }
 
+       /* 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)
+           && (!io->n.nt_hash) && (!io->n.lm_hash)) {
+               ldb_asprintf_errstring(ldb,
+                       "setup_io: "
+                       "It' 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(orig_msg, "userPassword") != NULL) ||
+                   (ldb_msg_find_element(orig_msg, "clearTextPassword") != NULL)) {
+                       return LDB_ERR_CONSTRAINT_VIOLATION;
+               }
+               return LDB_ERR_UNWILLING_TO_PERFORM;
+       }
+
        /* refuse the change if someone wants to compare against a plaintext
           or hash at the same time for a "password modify" operation... */
        if ((io->og.cleartext_utf8 || io->og.cleartext_utf16)
@@ -1713,25 +2408,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 {
@@ -1740,14 +2424,15 @@ static int setup_io(struct ph_context *ac,
                }
        } else {
                /* this shouldn't happen */
-               return LDB_ERR_OPERATIONS_ERROR;
+               return ldb_operr(ldb);
        }
 
        return LDB_SUCCESS;
 }
 
 static struct ph_context *ph_init_context(struct ldb_module *module,
-                                         struct ldb_request *req)
+                                         struct ldb_request *req,
+                                         bool userPassword)
 {
        struct ldb_context *ldb;
        struct ph_context *ac;
@@ -1762,6 +2447,7 @@ static struct ph_context *ph_init_context(struct ldb_module *module,
 
        ac->module = module;
        ac->req = req;
+       ac->userPassword = userPassword;
 
        return ac;
 }
@@ -1790,14 +2476,12 @@ 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_old_pw_checked = true;
+               ac->change = (struct dsdb_control_password_change *) ctrl->data;
 
-               /* Mark the "change old password checked" control as uncritical
-                * (done) */
+               /* Mark the "change" control as uncritical (done) */
                ctrl->critical = false;
        }
 }
@@ -1889,11 +2573,16 @@ 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;
 
@@ -1907,9 +2596,9 @@ static int get_domain_data_callback(struct ldb_request *req,
                lp_ctx = talloc_get_type(ldb_get_opaque(ldb, "loadparm"),
                                         struct loadparm_context);
 
-               ac->status->domain_data.dns_domain = lp_dnsdomain(lp_ctx);
-               ac->status->domain_data.realm = lp_realm(lp_ctx);
-               ac->status->domain_data.netbios_domain = lp_sam_name(lp_ctx);
+               ac->status->domain_data.dns_domain = lpcfg_dnsdomain(lp_ctx);
+               ac->status->domain_data.realm = lpcfg_realm(lp_ctx);
+               ac->status->domain_data.netbios_domain = lpcfg_sam_name(lp_ctx);
 
                ac->status->reject_reason = SAM_PWD_CHANGE_NO_ERROR;
 
@@ -1981,16 +2670,19 @@ static int build_domain_data_request(struct ph_context *ac)
                                              "minPwdAge",
                                              "minPwdLength",
                                              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)
@@ -2000,6 +2692,8 @@ static int password_hash_add(struct ldb_module *module, struct ldb_request *req)
        struct ldb_message_element *userPasswordAttr, *clearTextPasswordAttr,
                *ntAttr, *lmAttr;
        int ret;
+       struct ldb_control *bypass = NULL;
+       bool userPassword = dsdb_user_password_support(module, req, req);
 
        ldb = ldb_module_get_ctx(module);
 
@@ -2015,6 +2709,15 @@ static int password_hash_add(struct ldb_module *module, struct ldb_request *req)
                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_add (bypassing)\n");
+               return password_hash_bypass(module, req);
+       }
+
        /* nobody must touch password histories and 'supplementalCredentials' */
        if (ldb_msg_find_element(req->op.add.message, "ntPwdHistory")) {
                return LDB_ERR_UNWILLING_TO_PERFORM;
@@ -2029,7 +2732,16 @@ static int password_hash_add(struct ldb_module *module, struct ldb_request *req)
        /* If no part of this touches the 'userPassword' OR 'clearTextPassword'
         * OR 'unicodePwd' OR 'dBCSPwd' we don't need to make any changes. */
 
-       userPasswordAttr = ldb_msg_find_element(req->op.add.message, "userPassword");
+       userPasswordAttr = NULL;
+       if (userPassword) {
+               userPasswordAttr = ldb_msg_find_element(req->op.add.message,
+                                                       "userPassword");
+               /* MS-ADTS 3.1.1.3.1.5.2 */
+               if ((userPasswordAttr != NULL) &&
+                   (dsdb_functional_level(ldb) < DS_DOMAIN_FUNCTION_2003)) {
+                       return LDB_ERR_CONSTRAINT_VIOLATION;
+               }
+       }
        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");
@@ -2053,10 +2765,10 @@ 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);
+       ac = ph_init_context(module, req, userPassword);
        if (ac == NULL) {
                DEBUG(0,(__location__ ": %s\n", ldb_errstring(ldb)));
-               return LDB_ERR_OPERATIONS_ERROR;
+               return ldb_operr(ldb);
        }
        ph_apply_controls(ac);
 
@@ -2083,36 +2795,32 @@ static int password_hash_add_do_add(struct ph_context *ac)
                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_ERR_OPERATIONS_ERROR;
+               return ldb_operr(ldb);
        }
 
-       /* remove attributes that we just read into 'io' (handle also superfluous
-        * "password modify" trials - multiple attributes with the same name -
-        * on add operations) */
-       while (ldb_msg_find_element(msg, "userPassword") != NULL) {
+       /* remove attributes that we just read into 'io' */
+       if (ac->userPassword) {
                ldb_msg_remove_attr(msg, "userPassword");
        }
-       while (ldb_msg_find_element(msg, "clearTextPassword") != NULL) {
-               ldb_msg_remove_attr(msg, "clearTextPassword");
-       }
-       while (ldb_msg_find_element(msg, "unicodePwd") != NULL) {
-               ldb_msg_remove_attr(msg, "unicodePwd");
-       }
-       while (ldb_msg_find_element(msg, "dBCSPwd") != NULL) {
-               ldb_msg_remove_attr(msg, "dBCSPwd");
-       }
-
+       ldb_msg_remove_attr(msg, "clearTextPassword");
+       ldb_msg_remove_attr(msg, "unicodePwd");
+       ldb_msg_remove_attr(msg, "dBCSPwd");
        ldb_msg_remove_attr(msg, "pwdLastSet");
 
-       ldb = ldb_module_get_ctx(ac->module);
-
        ret = setup_password_fields(&io);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
 
+       ret = check_password_restrictions(&io);
+       if (ret != LDB_SUCCESS) {
+               return ret;
+       }
+
        if (io.g.nt_hash) {
                ret = samdb_msg_add_hash(ldb, ac, msg,
                                         "unicodePwd", io.g.nt_hash);
@@ -2128,7 +2836,7 @@ static int password_hash_add_do_add(struct ph_context *ac)
                }
        }
        if (io.g.nt_history_len > 0) {
-               ret = samdb_msg_add_hashes(ac, msg,
+               ret = samdb_msg_add_hashes(ldb, ac, msg,
                                           "ntPwdHistory",
                                           io.g.nt_history,
                                           io.g.nt_history_len);
@@ -2137,7 +2845,7 @@ static int password_hash_add_do_add(struct ph_context *ac)
                }
        }
        if (io.g.lm_history_len > 0) {
-               ret = samdb_msg_add_hashes(ac, msg,
+               ret = samdb_msg_add_hashes(ldb, ac, msg,
                                           "lmPwdHistory",
                                           io.g.lm_history,
                                           io.g.lm_history_len);
@@ -2164,6 +2872,7 @@ static int password_hash_add_do_add(struct ph_context *ac)
                                ac->req->controls,
                                ac, ph_op_callback,
                                ac->req);
+       LDB_REQ_SET_LOCATION(down_req);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
@@ -2182,6 +2891,8 @@ static int password_hash_modify(struct ldb_module *module, struct ldb_request *r
        struct ldb_message *msg;
        struct ldb_request *down_req;
        int ret;
+       struct ldb_control *bypass = NULL;
+       bool userPassword = dsdb_user_password_support(module, req, req);
 
        ldb = ldb_module_get_ctx(module);
 
@@ -2197,6 +2908,15 @@ static int password_hash_modify(struct ldb_module *module, struct ldb_request *r
                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 password_hash_bypass(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;
@@ -2214,7 +2934,17 @@ static int password_hash_modify(struct ldb_module *module, struct ldb_request *r
         * on these attributes. */
        attr_cnt = 0;
        for (l = passwordAttrs; *l != NULL; l++) {
+               if ((!userPassword) && (ldb_attr_cmp(*l, "userPassword") == 0)) {
+                       continue;
+               }
+
                if (ldb_msg_find_element(req->op.mod.message, *l) != NULL) {
+                       /* MS-ADTS 3.1.1.3.1.5.2 */
+                       if ((ldb_attr_cmp(*l, "userPassword") == 0) &&
+                           (dsdb_functional_level(ldb) < DS_DOMAIN_FUNCTION_2003)) {
+                               return LDB_ERR_CONSTRAINT_VIOLATION;
+                       }
+
                        ++attr_cnt;
                }
        }
@@ -2222,18 +2952,17 @@ static int password_hash_modify(struct ldb_module *module, struct ldb_request *r
                return ldb_next_request(module, req);
        }
 
-       ac = ph_init_context(module, req);
+       ac = ph_init_context(module, req, userPassword);
        if (!ac) {
                DEBUG(0,(__location__ ": %s\n", ldb_errstring(ldb)));
-               return LDB_ERR_OPERATIONS_ERROR;
+               return ldb_operr(ldb);
        }
        ph_apply_controls(ac);
 
        /* use a new message structure so that we can modify it */
        msg = ldb_msg_copy_shallow(ac, req->op.mod.message);
        if (msg == NULL) {
-               ldb_oom(ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
+               return ldb_oom(ldb);
        }
 
        /* - check for single-valued password attributes
@@ -2251,33 +2980,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_attr(msg, *l);
+                       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,
@@ -2307,6 +3043,7 @@ static int password_hash_modify(struct ldb_module *module, struct ldb_request *r
                                req->controls,
                                ac, ph_modify_callback,
                                req);
+       LDB_REQ_SET_LOCATION(down_req);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
@@ -2452,7 +3189,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;
        }
@@ -2462,7 +3199,10 @@ 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;
+       struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
+       struct loadparm_context *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;
@@ -2470,12 +3210,10 @@ static int password_hash_mod_do_mod(struct ph_context *ac)
        int ret;
        NTSTATUS status;
 
-       ldb = ldb_module_get_ctx(ac->module);
-
        /* use a new message structure so that we can modify it */
        msg = ldb_msg_new(ac);
        if (msg == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
+               return ldb_operr(ldb);
        }
 
        /* modify dn */
@@ -2492,11 +3230,11 @@ static int password_hash_mod_do_mod(struct ph_context *ac)
        
        /* Get the old password from the database */
        status = samdb_result_passwords(io.ac,
-                                       ldb_get_opaque(ldb, "loadparm"),
-                                       searched_msg,
+                                       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_ERR_OPERATIONS_ERROR;
+               return ldb_operr(ldb);
        }
 
        io.o.nt_history_len             = samdb_result_hashes(io.ac, searched_msg, "ntPwdHistory", &io.o.nt_history);
@@ -2508,6 +3246,11 @@ static int password_hash_mod_do_mod(struct ph_context *ac)
                return ret;
        }
 
+       ret = check_password_restrictions(&io);
+       if (ret != LDB_SUCCESS) {
+               return ret;
+       }
+
        /* make sure we replace all the old attributes */
        ret = ldb_msg_add_empty(msg, "unicodePwd", LDB_FLAG_MOD_REPLACE, NULL);
        ret = ldb_msg_add_empty(msg, "dBCSPwd", LDB_FLAG_MOD_REPLACE, NULL);
@@ -2531,7 +3274,7 @@ static int password_hash_mod_do_mod(struct ph_context *ac)
                }
        }
        if (io.g.nt_history_len > 0) {
-               ret = samdb_msg_add_hashes(ac, msg,
+               ret = samdb_msg_add_hashes(ldb, ac, msg,
                                           "ntPwdHistory",
                                           io.g.nt_history,
                                           io.g.nt_history_len);
@@ -2540,7 +3283,7 @@ static int password_hash_mod_do_mod(struct ph_context *ac)
                }
        }
        if (io.g.lm_history_len > 0) {
-               ret = samdb_msg_add_hashes(ac, msg,
+               ret = samdb_msg_add_hashes(ldb, ac, msg,
                                           "lmPwdHistory",
                                           io.g.lm_history,
                                           io.g.lm_history_len);
@@ -2567,6 +3310,7 @@ static int password_hash_mod_do_mod(struct ph_context *ac)
                                ac->req->controls,
                                ac, ph_op_callback,
                                ac->req);
+       LDB_REQ_SET_LOCATION(mod_req);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
@@ -2574,8 +3318,14 @@ 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)
+{
+       LDB_MODULE_CHECK_VERSION(version);
+       return ldb_register_module(&ldb_password_hash_module_ops);
+}