s4:dsdb/password_hash: split out a password_hash_needed() function
[metze/samba/wip.git] / source4 / dsdb / samdb / ldb_modules / password_hash.c
index 4644628b9f27a2942427cd854c8e2d9808639d34..70f9902d724cf0e3abafe3edda62588e74aa2232 100644 (file)
@@ -43,6 +43,7 @@
 #include "librpc/gen_ndr/ndr_drsblobs.h"
 #include "../lib/crypto/crypto.h"
 #include "param/param.h"
+#include "lib/krb5_wrap/krb5_samba.h"
 
 /* If we have decided there is a reason to work on this request, then
  * setup all the password hash types correctly.
@@ -645,18 +646,18 @@ static int setup_kerberos_keys(struct setup_password_fields_io *io)
 {
        struct ldb_context *ldb;
        krb5_error_code krb5_ret;
-       Principal *salt_principal;
-       krb5_salt salt;
+       krb5_principal salt_principal;
+       krb5_data salt;
        krb5_keyblock key;
        krb5_data cleartext_data;
 
        ldb = ldb_module_get_ctx(io->ac->module);
-       cleartext_data.data = io->n.cleartext_utf8->data;
+       cleartext_data.data = (char *)io->n.cleartext_utf8->data;
        cleartext_data.length = io->n.cleartext_utf8->length;
 
        /* Many, many thanks to lukeh@padl.com for this
         * algorithm, described in his Nov 10 2004 mail to
-        * samba-technical@samba.org */
+        * samba-technical@lists.samba.org */
 
        /*
         * Determine a salting principal
@@ -680,7 +681,7 @@ static int setup_kerberos_keys(struct setup_password_fields_io *io)
                        return ldb_oom(ldb);
                }
                
-               krb5_ret = krb5_make_principal(io->smb_krb5_context->krb5_context,
+               krb5_ret = smb_krb5_make_principal(io->smb_krb5_context->krb5_context,
                                               &salt_principal,
                                               io->ac->status->domain_data.realm,
                                               "host", saltbody, NULL);
@@ -698,12 +699,12 @@ static int setup_kerberos_keys(struct setup_password_fields_io *io)
                        p[0] = '\0';
                }
 
-               krb5_ret = krb5_make_principal(io->smb_krb5_context->krb5_context,
+               krb5_ret = smb_krb5_make_principal(io->smb_krb5_context->krb5_context,
                                               &salt_principal,
                                               io->ac->status->domain_data.realm,
                                               user_principal_name, NULL);
        } else {
-               krb5_ret = krb5_make_principal(io->smb_krb5_context->krb5_context,
+               krb5_ret = smb_krb5_make_principal(io->smb_krb5_context->krb5_context,
                                               &salt_principal,
                                               io->ac->status->domain_data.realm,
                                               io->u.sAMAccountName, NULL);
@@ -720,7 +721,7 @@ static int setup_kerberos_keys(struct setup_password_fields_io *io)
        /*
         * create salt from salt_principal
         */
-       krb5_ret = krb5_get_pw_salt(io->smb_krb5_context->krb5_context,
+       krb5_ret = smb_krb5_get_pw_salt(io->smb_krb5_context->krb5_context,
                                    salt_principal, &salt);
        krb5_free_principal(io->smb_krb5_context->krb5_context, salt_principal);
        if (krb5_ret) {
@@ -733,24 +734,26 @@ static int setup_kerberos_keys(struct setup_password_fields_io *io)
        }
        /* create a talloc copy */
        io->g.salt = talloc_strndup(io->ac,
-                                   (char *)salt.saltvalue.data,
-                                   salt.saltvalue.length);
-       krb5_free_salt(io->smb_krb5_context->krb5_context, salt);
+                                   (char *)salt.data,
+                                   salt.length);
+       kerberos_free_data_contents(io->smb_krb5_context->krb5_context, &salt);
        if (!io->g.salt) {
                return ldb_oom(ldb);
        }
-       salt.saltvalue.data     = discard_const(io->g.salt);
-       salt.saltvalue.length   = strlen(io->g.salt);
+       /* now use the talloced copy of the salt */
+       salt.data       = discard_const(io->g.salt);
+       salt.length     = strlen(io->g.salt);
 
        /*
         * create ENCTYPE_AES256_CTS_HMAC_SHA1_96 key out of
         * the salt and the cleartext password
         */
-       krb5_ret = krb5_string_to_key_data_salt(io->smb_krb5_context->krb5_context,
-                                               ENCTYPE_AES256_CTS_HMAC_SHA1_96,
-                                               cleartext_data,
-                                               salt,
-                                               &key);
+       krb5_ret = smb_krb5_create_key_from_string(io->smb_krb5_context->krb5_context,
+                                                  NULL,
+                                                  &salt,
+                                                  &cleartext_data,
+                                                  ENCTYPE_AES256_CTS_HMAC_SHA1_96,
+                                                  &key);
        if (krb5_ret) {
                ldb_asprintf_errstring(ldb,
                                       "setup_kerberos_keys: "
@@ -771,11 +774,12 @@ static int setup_kerberos_keys(struct setup_password_fields_io *io)
         * create ENCTYPE_AES128_CTS_HMAC_SHA1_96 key out of
         * the salt and the cleartext password
         */
-       krb5_ret = krb5_string_to_key_data_salt(io->smb_krb5_context->krb5_context,
-                                               ENCTYPE_AES128_CTS_HMAC_SHA1_96,
-                                               cleartext_data,
-                                               salt,
-                                               &key);
+       krb5_ret = smb_krb5_create_key_from_string(io->smb_krb5_context->krb5_context,
+                                                  NULL,
+                                                  &salt,
+                                                  &cleartext_data,
+                                                  ENCTYPE_AES128_CTS_HMAC_SHA1_96,
+                                                  &key);
        if (krb5_ret) {
                ldb_asprintf_errstring(ldb,
                                       "setup_kerberos_keys: "
@@ -796,11 +800,12 @@ static int setup_kerberos_keys(struct setup_password_fields_io *io)
         * create ENCTYPE_DES_CBC_MD5 key out of
         * the salt and the cleartext password
         */
-       krb5_ret = krb5_string_to_key_data_salt(io->smb_krb5_context->krb5_context,
-                                               ENCTYPE_DES_CBC_MD5,
-                                               cleartext_data,
-                                               salt,
-                                               &key);
+       krb5_ret = smb_krb5_create_key_from_string(io->smb_krb5_context->krb5_context,
+                                                  NULL,
+                                                  &salt,
+                                                  &cleartext_data,
+                                                  ENCTYPE_DES_CBC_MD5,
+                                                  &key);
        if (krb5_ret) {
                ldb_asprintf_errstring(ldb,
                                       "setup_kerberos_keys: "
@@ -821,11 +826,12 @@ static int setup_kerberos_keys(struct setup_password_fields_io *io)
         * create ENCTYPE_DES_CBC_CRC key out of
         * the salt and the cleartext password
         */
-       krb5_ret = krb5_string_to_key_data_salt(io->smb_krb5_context->krb5_context,
-                                               ENCTYPE_DES_CBC_CRC,
-                                               cleartext_data,
-                                               salt,
-                                               &key);
+       krb5_ret = smb_krb5_create_key_from_string(io->smb_krb5_context->krb5_context,
+                                                  NULL,
+                                                  &salt,
+                                                  &cleartext_data,
+                                                  ENCTYPE_DES_CBC_CRC,
+                                                  &key);
        if (krb5_ret) {
                ldb_asprintf_errstring(ldb,
                                       "setup_kerberos_keys: "
@@ -1368,7 +1374,7 @@ static int setup_primary_wdigest(struct setup_password_fields_io *io,
        }
 
        for (i=0; i < ARRAY_SIZE(wdigest); i++) {
-               struct MD5Context md5;
+               MD5_CTX md5;
                MD5Init(&md5);
                if (wdigest[i].nt4dom) {
                        MD5Update(&md5, wdigest[i].nt4dom->data, wdigest[i].nt4dom->length);
@@ -1681,6 +1687,7 @@ static int setup_supplemental_field(struct setup_password_fields_io *io)
 static int setup_last_set_field(struct setup_password_fields_io *io)
 {
        const struct ldb_message *msg = NULL;
+       struct timeval tv = { .tv_sec = 0 };
 
        switch (io->ac->req->operation) {
        case LDB_ADD:
@@ -1711,7 +1718,8 @@ static int setup_last_set_field(struct setup_password_fields_io *io)
        }
 
        /* set it as now */
-       unix_to_nt_time(&io->g.last_set, time(NULL));
+       GetTimeOfDay(&tv);
+       io->g.last_set = timeval_to_nttime(&tv);
 
        return LDB_SUCCESS;
 }
@@ -1872,11 +1880,116 @@ static int setup_password_fields(struct setup_password_fields_io *io)
        return LDB_SUCCESS;
 }
 
+static int make_error_and_update_badPwdCount(struct setup_password_fields_io *io)
+{
+       struct ldb_context *ldb = ldb_module_get_ctx(io->ac->module);
+       struct ldb_message *mod_msg = NULL;
+       NTSTATUS status;
+       int ret;
+
+       status = dsdb_update_bad_pwd_count(io->ac, ldb,
+                                          io->ac->search_res->message,
+                                          io->ac->dom_res->message,
+                                          &mod_msg);
+       if (!NT_STATUS_IS_OK(status)) {
+               goto done;
+       }
+
+       if (mod_msg == NULL) {
+               goto done;
+       }
+
+       /*
+        * OK, horrible semantics ahead.
+        *
+        * - We need to abort any existing transaction
+        * - create a transaction arround the badPwdCount update
+        * - re-open the transaction so the upper layer
+        *   doesn't know what happened.
+        *
+        * This is needed because returning an error to the upper
+        * layer will cancel the transaction and undo the badPwdCount
+        * update.
+        */
+
+       /*
+        * Checking errors here is a bit pointless.
+        * What can we do if we can't end the transaction?
+        */
+       ret = ldb_next_del_trans(io->ac->module);
+       if (ret != LDB_SUCCESS) {
+               ldb_debug(ldb, LDB_DEBUG_FATAL,
+                         "Failed to abort transaction prior to update of badPwdCount of %s: %s",
+                         ldb_dn_get_linearized(io->ac->search_res->message->dn),
+                         ldb_errstring(ldb));
+               /*
+                * just return the original error
+                */
+               goto done;
+       }
+
+       /* Likewise, what should we do if we can't open a new transaction? */
+       ret = ldb_next_start_trans(io->ac->module);
+       if (ret != LDB_SUCCESS) {
+               ldb_debug(ldb, LDB_DEBUG_ERROR,
+                         "Failed to open transaction to update badPwdCount of %s: %s",
+                         ldb_dn_get_linearized(io->ac->search_res->message->dn),
+                         ldb_errstring(ldb));
+               /*
+                * just return the original error
+                */
+               goto done;
+       }
+
+       ret = dsdb_module_modify(io->ac->module, mod_msg,
+                                DSDB_FLAG_NEXT_MODULE,
+                                io->ac->req);
+       if (ret != LDB_SUCCESS) {
+               ldb_debug(ldb, LDB_DEBUG_ERROR,
+                         "Failed to update badPwdCount of %s: %s",
+                         ldb_dn_get_linearized(io->ac->search_res->message->dn),
+                         ldb_errstring(ldb));
+               /*
+                * We can only ignore this...
+                */
+       }
+
+       ret = ldb_next_end_trans(io->ac->module);
+       if (ret != LDB_SUCCESS) {
+               ldb_debug(ldb, LDB_DEBUG_ERROR,
+                         "Failed to close transaction to update badPwdCount of %s: %s",
+                         ldb_dn_get_linearized(io->ac->search_res->message->dn),
+                         ldb_errstring(ldb));
+               /*
+                * We can only ignore this...
+                */
+       }
+
+       ret = ldb_next_start_trans(io->ac->module);
+       if (ret != LDB_SUCCESS) {
+               ldb_debug(ldb, LDB_DEBUG_ERROR,
+                         "Failed to open transaction after update of badPwdCount of %s: %s",
+                         ldb_dn_get_linearized(io->ac->search_res->message->dn),
+                         ldb_errstring(ldb));
+               /*
+                * We can only ignore this...
+                */
+       }
+
+done:
+       ret = LDB_ERR_CONSTRAINT_VIOLATION;
+       ldb_asprintf_errstring(ldb,
+                              "%08X: %s - check_password_restrictions: "
+                              "The old password specified doesn't match!",
+                              W_ERROR_V(WERR_INVALID_PASSWORD),
+                              ldb_strerror(ret));
+       return ret;
+}
+
 static int check_password_restrictions(struct setup_password_fields_io *io)
 {
        struct ldb_context *ldb;
        int ret;
-       enum samr_ValidationStatus stat;
 
        ldb = ldb_module_get_ctx(io->ac->module);
 
@@ -1896,25 +2009,8 @@ static int check_password_restrictions(struct setup_password_fields_io *io)
                /* 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;
+                       if (!io->o.nt_hash || memcmp(io->og.nt_hash->hash, io->o.nt_hash->hash, 16) != 0) {
+                               return make_error_and_update_badPwdCount(io);
                        }
 
                        nt_hash_checked = true;
@@ -1925,26 +2021,9 @@ static int check_password_restrictions(struct setup_password_fields_io *io)
                 * 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->o.lm_hash && !nt_hash_checked)
+                           || (io->o.lm_hash && memcmp(io->og.lm_hash->hash, io->o.lm_hash->hash, 16) != 0)) {
+                               return make_error_and_update_badPwdCount(io);
                        }
                }
        }
@@ -1954,16 +2033,30 @@ static int check_password_restrictions(struct setup_password_fields_io *io)
                return LDB_SUCCESS;
        }
 
+       /* Password minimum age: yes, this is a minus. The ages are in negative 100nsec units! */
+       if ((io->u.pwdLastSet - io->ac->status->domain_data.minPwdAge > io->g.last_set) &&
+           !io->ac->pwd_reset)
+       {
+               ret = LDB_ERR_CONSTRAINT_VIOLATION;
+               ldb_asprintf_errstring(ldb,
+                       "%08X: %s - check_password_restrictions: "
+                       "password is too young to change!",
+                       W_ERROR_V(WERR_PASSWORD_RESTRICTION),
+                       ldb_strerror(ret));
+               return ret;
+       }
+
        /*
         * Fundamental password checks done by the call
         * "samdb_check_password".
         * It is also in use by "dcesrv_samr_ValidatePassword".
         */
        if (io->n.cleartext_utf8 != NULL) {
-               stat = samdb_check_password(io->n.cleartext_utf8,
-                                           io->ac->status->domain_data.pwdProperties,
-                                           io->ac->status->domain_data.minPwdLength);
-               switch (stat) {
+               enum samr_ValidationStatus vstat;
+               vstat = samdb_check_password(io->n.cleartext_utf8,
+                                            io->ac->status->domain_data.pwdProperties,
+                                            io->ac->status->domain_data.minPwdLength);
+               switch (vstat) {
                case SAMR_VALIDATION_STATUS_SUCCESS:
                                /* perfect -> proceed! */
                        break;
@@ -2028,7 +2121,7 @@ static int check_password_restrictions(struct setup_password_fields_io *io)
 
                /* checks the LM hash password history */
                for (i = 0; i < io->o.lm_history_len; i++) {
-                       ret = memcmp(io->n.nt_hash, io->o.lm_history[i].hash, 16);
+                       ret = memcmp(io->n.lm_hash, io->o.lm_history[i].hash, 16);
                        if (ret == 0) {
                                ret = LDB_ERR_CONSTRAINT_VIOLATION;
                                ldb_asprintf_errstring(ldb,
@@ -2064,17 +2157,6 @@ static int check_password_restrictions(struct setup_password_fields_io *io)
                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;
 }
 
@@ -2147,9 +2229,8 @@ 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);
+       struct loadparm_context *lp_ctx = talloc_get_type(
+               ldb_get_opaque(ldb, "loadparm"), struct loadparm_context);
        int ret;
 
        ZERO_STRUCTP(io);
@@ -2157,7 +2238,6 @@ static int setup_io(struct ph_context *ac,
        /* Some operations below require kerberos contexts */
 
        if (smb_krb5_init_context(ac,
-                                 ldb_get_event_context(ldb),
                                  (struct loadparm_context *)ldb_get_opaque(ldb, "loadparm"),
                                  &io->smb_krb5_context) != 0) {
                return ldb_operr(ldb);
@@ -2182,6 +2262,22 @@ static int setup_io(struct ph_context *ac,
                return LDB_ERR_CONSTRAINT_VIOLATION;
        }
 
+       if (io->u.userAccountControl & UF_INTERDOMAIN_TRUST_ACCOUNT) {
+               struct ldb_control *permit_trust = ldb_request_get_control(ac->req,
+                               DSDB_CONTROL_PERMIT_INTERDOMAIN_TRUST_UAC_OID);
+
+               if (permit_trust == NULL) {
+                       ret = LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
+                       ldb_asprintf_errstring(ldb,
+                               "%08X: %s - setup_io: changing the interdomain trust password "
+                               "on %s not allowed via LDAP. Use LSA or NETLOGON",
+                               W_ERROR_V(WERR_ACCESS_DENIED),
+                               ldb_strerror(ret),
+                               ldb_dn_get_linearized(searched_msg->dn));
+                       return ret;
+               }
+       }
+
        /* Only non-trust accounts have restrictions (possibly this test is the
         * wrong way around, but we like to be restrictive if possible */
        io->u.restrictions = !(io->u.userAccountControl
@@ -2201,6 +2297,29 @@ static int setup_io(struct ph_context *ac,
                }
        }
 
+       if (io->n.cleartext_utf8 != NULL) {
+               struct ldb_val *cleartext_utf8_blob;
+               char *p;
+
+               cleartext_utf8_blob = talloc(io->ac, struct ldb_val);
+               if (!cleartext_utf8_blob) {
+                       return ldb_oom(ldb);
+               }
+
+               *cleartext_utf8_blob = *io->n.cleartext_utf8;
+
+               /* make sure we have a null terminated string */
+               p = talloc_strndup(cleartext_utf8_blob,
+                                  (const char *)io->n.cleartext_utf8->data,
+                                  io->n.cleartext_utf8->length);
+               if ((p == NULL) && (io->n.cleartext_utf8->length > 0)) {
+                       return ldb_oom(ldb);
+               }
+               cleartext_utf8_blob->data = (uint8_t *)p;
+
+               io->n.cleartext_utf8 = cleartext_utf8_blob;
+       }
+
        ret = msg_find_old_and_new_pwd_val(orig_msg, "clearTextPassword",
                                           ac->req->operation,
                                           &io->n.cleartext_utf16,
@@ -2589,7 +2708,7 @@ static int get_domain_data_callback(struct ldb_request *req,
        struct ldb_context *ldb;
        struct ph_context *ac;
        struct loadparm_context *lp_ctx;
-       int ret;
+       int ret = LDB_SUCCESS;
 
        ac = talloc_get_type(req->context, struct ph_context);
        ldb = ldb_module_get_ctx(ac->module);
@@ -2638,8 +2757,6 @@ static int get_domain_data_callback(struct ldb_request *req,
                ac->status->domain_data.store_cleartext =
                        ac->status->domain_data.pwdProperties & DOMAIN_PASSWORD_STORE_CLEARTEXT;
 
-               talloc_free(ares);
-
                /* For a domain DN, this puts things in dotted notation */
                /* For builtin domains, this will give details for the host,
                 * but that doesn't really matter, as it's just used for salt
@@ -2654,6 +2771,15 @@ static int get_domain_data_callback(struct ldb_request *req,
 
                ac->status->reject_reason = SAM_PWD_CHANGE_NO_ERROR;
 
+               if (ac->dom_res != NULL) {
+                       talloc_free(ares);
+
+                       ldb_set_errstring(ldb, "Too many results");
+                       ret = LDB_ERR_OPERATIONS_ERROR;
+                       goto done;
+               }
+
+               ac->dom_res = talloc_steal(ac, ares);
                ret = LDB_SUCCESS;
                break;
 
@@ -2721,6 +2847,8 @@ static int build_domain_data_request(struct ph_context *ac)
                                              "maxPwdAge",
                                              "minPwdAge",
                                              "minPwdLength",
+                                             "lockoutThreshold",
+                                             "lockOutObservationWindow",
                                              NULL };
        int ret;
 
@@ -2737,21 +2865,44 @@ static int build_domain_data_request(struct ph_context *ac)
        return ret;
 }
 
-static int password_hash_add(struct ldb_module *module, struct ldb_request *req)
+static int password_hash_needed(struct ldb_module *module,
+                               struct ldb_request *req,
+                               struct ph_context **_ac)
 {
-       struct ldb_context *ldb;
-       struct ph_context *ac;
-       struct ldb_message_element *userPasswordAttr, *clearTextPasswordAttr,
-               *ntAttr, *lmAttr;
-       int ret;
+       struct ldb_context *ldb = ldb_module_get_ctx(module);
+       const char *operation = NULL;
+       const struct ldb_message *msg = NULL;
+       struct ph_context *ac = NULL;
+       const char *passwordAttrs[] = {
+               "userPassword",
+               "clearTextPassword",
+               "unicodePwd",
+               "dBCSPwd",
+               NULL
+       };
+       const char **a = NULL;
+       unsigned int attr_cnt = 0;
        struct ldb_control *bypass = NULL;
        bool userPassword = dsdb_user_password_support(module, req, req);
 
-       ldb = ldb_module_get_ctx(module);
+       *_ac = NULL;
 
-       ldb_debug(ldb, LDB_DEBUG_TRACE, "password_hash_add\n");
+       ldb_debug(ldb, LDB_DEBUG_TRACE, "password_hash_needed\n");
+
+       switch (req->operation) {
+       case LDB_ADD:
+               operation = "add";
+               msg = req->op.add.message;
+               break;
+       case LDB_MODIFY:
+               operation = "modify";
+               msg = req->op.mod.message;
+               break;
+       default:
+               return ldb_next_request(module, req);
+       }
 
-       if (ldb_dn_is_special(req->op.add.message->dn)) { /* do not manipulate our control entries */
+       if (ldb_dn_is_special(msg->dn)) { /* do not manipulate our control entries */
                return ldb_next_request(module, req);
        }
 
@@ -2760,48 +2911,84 @@ static int password_hash_add(struct ldb_module *module, struct ldb_request *req)
        if (bypass != NULL) {
                /* Mark the "bypass" control as uncritical (done) */
                bypass->critical = false;
-               ldb_debug(ldb, LDB_DEBUG_TRACE, "password_hash_add (bypassing)\n");
+               ldb_debug(ldb, LDB_DEBUG_TRACE,
+                         "password_hash_needed(%s) (bypassing)\n",
+                         operation);
                return password_hash_bypass(module, req);
        }
 
        /* nobody must touch password histories and 'supplementalCredentials' */
-       if (ldb_msg_find_element(req->op.add.message, "ntPwdHistory")) {
+       if (ldb_msg_find_element(msg, "ntPwdHistory")) {
                return LDB_ERR_UNWILLING_TO_PERFORM;
        }
-       if (ldb_msg_find_element(req->op.add.message, "lmPwdHistory")) {
+       if (ldb_msg_find_element(msg, "lmPwdHistory")) {
                return LDB_ERR_UNWILLING_TO_PERFORM;
        }
-       if (ldb_msg_find_element(req->op.add.message, "supplementalCredentials")) {
+       if (ldb_msg_find_element(msg, "supplementalCredentials")) {
                return LDB_ERR_UNWILLING_TO_PERFORM;
        }
 
-       /* If no part of this touches the 'userPassword' OR 'clearTextPassword'
-        * OR 'unicodePwd' OR 'dBCSPwd' we don't need to make any changes. */
+       /*
+        * If no part of this touches the 'userPassword' OR 'clearTextPassword'
+        * OR 'unicodePwd' OR 'dBCSPwd' we don't need to make any changes.
+        * For password changes/set there should be a 'delete' or a 'modify'
+        * on these attributes.
+        */
+       for (a = passwordAttrs; *a != NULL; a++) {
+               if ((!userPassword) && (ldb_attr_cmp(*a, "userPassword") == 0)) {
+                       continue;
+               }
+
+               if (ldb_msg_find_element(msg, *a) != NULL) {
+                       /* MS-ADTS 3.1.1.3.1.5.2 */
+                       if ((ldb_attr_cmp(*a, "userPassword") == 0) &&
+                           (dsdb_functional_level(ldb) < DS_DOMAIN_FUNCTION_2003)) {
+                               return LDB_ERR_CONSTRAINT_VIOLATION;
+                       }
 
-       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;
+                       ++attr_cnt;
                }
        }
-       clearTextPasswordAttr = ldb_msg_find_element(req->op.add.message, "clearTextPassword");
-       ntAttr = ldb_msg_find_element(req->op.add.message, "unicodePwd");
-       lmAttr = ldb_msg_find_element(req->op.add.message, "dBCSPwd");
 
-       if ((!userPasswordAttr) && (!clearTextPasswordAttr) && (!ntAttr) && (!lmAttr)) {
+       if (attr_cnt == 0) {
                return ldb_next_request(module, req);
        }
 
+       ac = ph_init_context(module, req, userPassword);
+       if (!ac) {
+               DEBUG(0,(__location__ ": %s\n", ldb_errstring(ldb)));
+               return ldb_operr(ldb);
+       }
+       ph_apply_controls(ac);
+
+       *_ac = ac;
+       return LDB_SUCCESS;
+}
+
+static int password_hash_add(struct ldb_module *module, struct ldb_request *req)
+{
+       struct ldb_context *ldb = ldb_module_get_ctx(module);
+       struct ph_context *ac = NULL;
+       int ret;
+
+       ldb_debug(ldb, LDB_DEBUG_TRACE, "password_hash_add\n");
+
+       ret = password_hash_needed(module, req, &ac);
+       if (ret != LDB_SUCCESS) {
+               return ret;
+       }
+       if (ac == NULL) {
+               return ret;
+       }
+
        /* Make sure we are performing the password set action on a (for us)
         * valid object. Those are instances of either "user" and/or
         * "inetOrgPerson". Otherwise continue with the submodules. */
        if ((!ldb_msg_check_string_attribute(req->op.add.message, "objectClass", "user"))
                && (!ldb_msg_check_string_attribute(req->op.add.message, "objectClass", "inetOrgPerson"))) {
 
+               TALLOC_FREE(ac);
+
                if (ldb_msg_find_element(req->op.add.message, "clearTextPassword") != NULL) {
                        ldb_set_errstring(ldb,
                                          "'clearTextPassword' is only allowed on objects of class 'user' and/or 'inetOrgPerson'!");
@@ -2811,13 +2998,6 @@ static int password_hash_add(struct ldb_module *module, struct ldb_request *req)
                return ldb_next_request(module, req);
        }
 
-       ac = ph_init_context(module, req, userPassword);
-       if (ac == NULL) {
-               DEBUG(0,(__location__ ": %s\n", ldb_errstring(ldb)));
-               return ldb_operr(ldb);
-       }
-       ph_apply_controls(ac);
-
        /* get user domain data */
        ret = build_domain_data_request(ac);
        if (ret != LDB_SUCCESS) {
@@ -2928,76 +3108,25 @@ static int password_hash_add_do_add(struct ph_context *ac)
 
 static int password_hash_modify(struct ldb_module *module, struct ldb_request *req)
 {
-       struct ldb_context *ldb;
-       struct ph_context *ac;
+       struct ldb_context *ldb = ldb_module_get_ctx(module);
+       struct ph_context *ac = NULL;
        const char *passwordAttrs[] = { "userPassword", "clearTextPassword",
                "unicodePwd", "dBCSPwd", NULL }, **l;
-       unsigned int attr_cnt, del_attr_cnt, add_attr_cnt, rep_attr_cnt;
+       unsigned int del_attr_cnt, add_attr_cnt, rep_attr_cnt;
        struct ldb_message_element *passwordAttr;
        struct ldb_message *msg;
        struct ldb_request *down_req;
        int ret;
-       struct ldb_control *bypass = NULL;
-       bool userPassword = dsdb_user_password_support(module, req, req);
-
-       ldb = ldb_module_get_ctx(module);
 
        ldb_debug(ldb, LDB_DEBUG_TRACE, "password_hash_modify\n");
 
-       if (ldb_dn_is_special(req->op.mod.message->dn)) { /* do not manipulate our control entries */
-               return ldb_next_request(module, req);
-       }
-       
-       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;
-       }
-       if (ldb_msg_find_element(req->op.mod.message, "lmPwdHistory")) {
-               return LDB_ERR_UNWILLING_TO_PERFORM;
-       }
-       if (ldb_msg_find_element(req->op.mod.message, "supplementalCredentials")) {
-               return LDB_ERR_UNWILLING_TO_PERFORM;
-       }
-
-       /* If no part of this touches the 'userPassword' OR 'clearTextPassword'
-        * OR 'unicodePwd' OR 'dBCSPwd' we don't need to make any changes.
-        * For password changes/set there should be a 'delete' or a 'modify'
-        * on these attributes. */
-       attr_cnt = 0;
-       for (l = passwordAttrs; *l != NULL; l++) {
-               if ((!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;
-               }
-       }
-       if (attr_cnt == 0) {
-               return ldb_next_request(module, req);
+       ret = password_hash_needed(module, req, &ac);
+       if (ret != LDB_SUCCESS) {
+               return ret;
        }
-
-       ac = ph_init_context(module, req, userPassword);
-       if (!ac) {
-               DEBUG(0,(__location__ ": %s\n", ldb_errstring(ldb)));
-               return ldb_operr(ldb);
+       if (ac == NULL) {
+               return ret;
        }
-       ph_apply_controls(ac);
 
        /* use a new message structure so that we can modify it */
        msg = ldb_msg_copy_shallow(ac, req->op.mod.message);
@@ -3126,7 +3255,7 @@ static int ph_mod_search_callback(struct ldb_request *req, struct ldb_reply *are
 {
        struct ldb_context *ldb;
        struct ph_context *ac;
-       int ret;
+       int ret = LDB_SUCCESS;
 
        ac = talloc_get_type(req->context, struct ph_context);
        ldb = ldb_module_get_ctx(ac->module);
@@ -3206,6 +3335,7 @@ static int password_hash_mod_search_self(struct ph_context *ac)
        struct ldb_context *ldb;
        static const char * const attrs[] = { "objectClass",
                                              "userAccountControl",
+                                             "msDS-User-Account-Control-Computed",
                                              "pwdLastSet",
                                              "sAMAccountName",
                                              "objectSid",
@@ -3215,6 +3345,9 @@ static int password_hash_mod_search_self(struct ph_context *ac)
                                              "ntPwdHistory",
                                              "dBCSPwd",
                                              "unicodePwd",
+                                             "badPasswordTime",
+                                             "badPwdCount",
+                                             "lockoutTime",
                                              NULL };
        struct ldb_request *search_req;
        int ret;
@@ -3268,12 +3401,34 @@ static int password_hash_mod_do_mod(struct ph_context *ac)
                return ret;
        }
        
-       /* Get the old password from the database */
-       status = samdb_result_passwords(io.ac,
-                                       lp_ctx,
-                                       discard_const_p(struct ldb_message, searched_msg),
-                                       &io.o.lm_hash, &io.o.nt_hash);
+       if (io.ac->pwd_reset) {
+               /* Get the old password from the database */
+               status = samdb_result_passwords_no_lockout(io.ac,
+                                                          lp_ctx,
+                                                          discard_const_p(struct ldb_message, searched_msg),
+                                                          &io.o.lm_hash,
+                                                          &io.o.nt_hash);
+       } else {
+               /* Get the old password from the database */
+               status = samdb_result_passwords(io.ac,
+                                               lp_ctx,
+                                               discard_const_p(struct ldb_message, searched_msg),
+                                               &io.o.lm_hash, &io.o.nt_hash);
+       }
+
+       if (NT_STATUS_EQUAL(status, NT_STATUS_ACCOUNT_LOCKED_OUT)) {
+               ldb_asprintf_errstring(ldb,
+                                      "%08X: check_password: "
+                                      "Password change not permitted, account locked out!",
+                                      W_ERROR_V(WERR_ACCOUNT_LOCKED_OUT));
+               return LDB_ERR_CONSTRAINT_VIOLATION;
+       }
+
        if (!NT_STATUS_IS_OK(status)) {
+               /*
+                * This only happens if the database has gone weird,
+                * not if we are just missing the passwords
+                */
                return ldb_operr(ldb);
        }