krb5-samba: interdomain trust uses different salt principal
[samba.git] / source4 / dsdb / samdb / ldb_modules / password_hash.c
index 7d38d215f16bc9157b64b1ce86f043d67bbddfa2..5f5710330044bb4dc37b4a76bf08866a42b1fc1f 100644 (file)
@@ -95,6 +95,8 @@ struct ph_context {
        struct ldb_request *dom_req;
        struct ldb_reply *dom_res;
 
+       struct ldb_reply *pso_res;
+
        struct ldb_reply *search_res;
 
        struct ldb_message *update_msg;
@@ -113,6 +115,7 @@ struct ph_context {
        bool pwd_last_set_bypass;
        bool pwd_last_set_default;
        bool smartcard_reset;
+       const char **userPassword_schemes;
 };
 
 
@@ -127,7 +130,6 @@ struct setup_password_fields_io {
                NTTIME pwdLastSet;
                const char *sAMAccountName;
                const char *user_principal_name;
-               bool is_computer;
                bool is_krbtgt;
                uint32_t restrictions;
                struct dom_sid *account_sid;
@@ -670,69 +672,24 @@ static int setup_kerberos_keys(struct setup_password_fields_io *io)
 {
        struct ldb_context *ldb;
        krb5_error_code krb5_ret;
-       krb5_principal salt_principal;
+       char *salt_principal = NULL;
+       char *salt_data = NULL;
        krb5_data salt;
        krb5_keyblock key;
        krb5_data cleartext_data;
+       uint32_t uac_flags = 0;
 
        ldb = ldb_module_get_ctx(io->ac->module);
        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@lists.samba.org */
-
-       /*
-        * Determine a salting principal
-        */
-       if (io->u.is_computer) {
-               char *name;
-               char *saltbody;
-
-               name = strlower_talloc(io->ac, io->u.sAMAccountName);
-               if (!name) {
-                       return ldb_oom(ldb);
-               }
-
-               if (name[strlen(name)-1] == '$') {
-                       name[strlen(name)-1] = '\0';
-               }
-
-               saltbody = talloc_asprintf(io->ac, "%s.%s", name,
-                                          io->ac->status->domain_data.dns_domain);
-               if (!saltbody) {
-                       return ldb_oom(ldb);
-               }
-               
-               krb5_ret = smb_krb5_make_principal(io->smb_krb5_context->krb5_context,
-                                              &salt_principal,
-                                              io->ac->status->domain_data.realm,
-                                              "host", saltbody, NULL);
-       } else if (io->u.user_principal_name) {
-               char *user_principal_name;
-               char *p;
-
-               user_principal_name = talloc_strdup(io->ac, io->u.user_principal_name);
-               if (!user_principal_name) {
-                       return ldb_oom(ldb);
-               }
-
-               p = strchr(user_principal_name, '@');
-               if (p) {
-                       p[0] = '\0';
-               }
-
-               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 = smb_krb5_make_principal(io->smb_krb5_context->krb5_context,
-                                              &salt_principal,
-                                              io->ac->status->domain_data.realm,
-                                              io->u.sAMAccountName, NULL);
-       }
+       uac_flags = io->u.userAccountControl & UF_ACCOUNT_TYPE_MASK;
+       krb5_ret = smb_krb5_salt_principal(io->ac->status->domain_data.realm,
+                                          io->u.sAMAccountName,
+                                          io->u.user_principal_name,
+                                          uac_flags,
+                                          io->ac,
+                                          &salt_principal);
        if (krb5_ret) {
                ldb_asprintf_errstring(ldb,
                                       "setup_kerberos_keys: "
@@ -745,9 +702,8 @@ static int setup_kerberos_keys(struct setup_password_fields_io *io)
        /*
         * create salt from salt_principal
         */
-       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);
+       krb5_ret = smb_krb5_salt_principal2data(io->smb_krb5_context->krb5_context,
+                                               salt_principal, io->ac, &salt_data);
        if (krb5_ret) {
                ldb_asprintf_errstring(ldb,
                                       "setup_kerberos_keys: "
@@ -756,14 +712,8 @@ static int setup_kerberos_keys(struct setup_password_fields_io *io)
                                                                  krb5_ret, io->ac));
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       /* create a talloc copy */
-       io->g.salt = talloc_strndup(io->ac,
-                                   (char *)salt.data,
-                                   salt.length);
-       smb_krb5_free_data_contents(io->smb_krb5_context->krb5_context, &salt);
-       if (!io->g.salt) {
-               return ldb_oom(ldb);
-       }
+       io->g.salt = salt_data;
+
        /* now use the talloced copy of the salt */
        salt.data       = discard_const(io->g.salt);
        salt.length     = strlen(io->g.salt);
@@ -1120,8 +1070,8 @@ static int setup_primary_wdigest(struct setup_password_fields_io *io,
                DATA_BLOB *nt4dom;
        } wdigest[] = {
        /*
-        * See
-        * http://technet2.microsoft.com/WindowsServer/en/library/717b450c-f4a0-4cc9-86f4-cc0633aae5f91033.mspx?mfr=true
+        * See 3.1.1.8.11.3.1 WDIGEST_CREDENTIALS Construction
+        *     https://msdn.microsoft.com/en-us/library/cc245680.aspx
         * for what precalculated hashes are supposed to be stored...
         *
         * I can't reproduce all values which should contain "Digest" as realm,
@@ -1228,8 +1178,17 @@ static int setup_primary_wdigest(struct setup_password_fields_io *io,
                .user   = &sAMAccountName_l,
                .realm  = &netbios_domain_u,
                },
-       /* 
+       /*
         * sAMAccountName, dns_domain
+        *
+        * TODO:
+        * Windows preserves the case of the DNS domain,
+        * Samba lower cases the domain at provision time
+        * This means that for mixed case Domains, the WDigest08 hash
+        * calculated by Samba differs from that calculated by Windows.
+        * Until we get a real world use case this will remain a known
+        * bug, as changing the case could have unforeseen impacts.
+        *
         */
                {
                .user   = &sAMAccountName,
@@ -1417,6 +1376,217 @@ static int setup_primary_wdigest(struct setup_password_fields_io *io,
        return LDB_SUCCESS;
 }
 
+#define SHA_SALT_PERMITTED_CHARS "abcdefghijklmnopqrstuvwxyz" \
+                                "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
+                                "0123456789./"
+#define SHA_SALT_SIZE 16
+#define SHA_256_SCHEME "CryptSHA256"
+#define SHA_512_SCHEME "CryptSHA512"
+#define CRYPT "{CRYPT}"
+#define SHA_ID_LEN 3
+#define SHA_256_ALGORITHM_ID 5
+#define SHA_512_ALGORITHM_ID 6
+#define ROUNDS_PARAMETER "rounds="
+
+/*
+ * Extract the crypt (3) algorithm number and number of hash rounds from the
+ * supplied scheme string
+ */
+static bool parse_scheme(const char *scheme, int *algorithm, int *rounds) {
+
+       const char *rp = NULL; /* Pointer to the 'rounds=' option */
+       char digits[21];       /* digits extracted from the rounds option */
+       int i = 0;             /* loop index variable */
+
+       if (strncasecmp(SHA_256_SCHEME, scheme, strlen(SHA_256_SCHEME)) == 0) {
+               *algorithm = SHA_256_ALGORITHM_ID;
+       } else if (strncasecmp(SHA_512_SCHEME, scheme, strlen(SHA_256_SCHEME))
+                  == 0) {
+               *algorithm = SHA_512_ALGORITHM_ID;
+       } else {
+               return false;
+       }
+
+       rp = strcasestr(scheme, ROUNDS_PARAMETER);
+       if (rp == NULL) {
+               /* No options specified, use crypt default number of rounds */
+               *rounds = 0;
+               return true;
+       }
+       rp += strlen(ROUNDS_PARAMETER);
+       for (i = 0; isdigit(rp[i]) && i < (sizeof(digits) - 1); i++) {
+               digits[i] = rp[i];
+       }
+       digits[i] = '\0';
+       *rounds = atoi(digits);
+       return true;
+}
+
+/*
+ * Calculate the password hash specified by scheme, and return it in
+ * hash_value
+ */
+static int setup_primary_userPassword_hash(
+       TALLOC_CTX *ctx,
+       struct setup_password_fields_io *io,
+       const char* scheme,
+       struct package_PrimaryUserPasswordValue *hash_value)
+{
+       struct ldb_context *ldb = ldb_module_get_ctx(io->ac->module);
+       const char *salt = NULL;        /* Randomly generated salt */
+       const char *cmd = NULL;         /* command passed to crypt */
+       const char *hash = NULL;        /* password hash generated by crypt */
+       int algorithm = 0;              /* crypt hash algorithm number */
+       int rounds = 0;                 /* The number of hash rounds */
+       DATA_BLOB *hash_blob = NULL;
+       TALLOC_CTX *frame = talloc_stackframe();
+#ifdef HAVE_CRYPT_R
+       struct crypt_data crypt_data;   /* working storage used by crypt */
+#endif
+
+       /* Genrate a random password salt */
+       salt = generate_random_str_list(frame,
+                                       SHA_SALT_SIZE,
+                                       SHA_SALT_PERMITTED_CHARS);
+       if (salt == NULL) {
+               TALLOC_FREE(frame);
+               return ldb_oom(ldb);
+       }
+
+       /* determine the hashing algoritm and number of rounds*/
+       if (!parse_scheme(scheme, &algorithm, &rounds)) {
+               ldb_asprintf_errstring(
+                       ldb,
+                       "setup_primary_userPassword: Invalid scheme of [%s] "
+                       "specified for 'password hash userPassword schemes' in "
+                       "samba.conf",
+                       scheme);
+               TALLOC_FREE(frame);
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+       hash_value->scheme = talloc_strdup(ctx, CRYPT);
+       hash_value->scheme_len = strlen(CRYPT) + 1;
+
+       /* generate the id/salt parameter used by crypt */
+       if (rounds) {
+               cmd = talloc_asprintf(frame,
+                                     "$%d$rounds=%d$%s",
+                                     algorithm,
+                                     rounds,
+                                     salt);
+       } else {
+               cmd = talloc_asprintf(frame, "$%d$%s", algorithm, salt);
+       }
+
+       /*
+        * Relies on the assertion that cleartext_utf8->data is a zero
+        * terminated UTF-8 string
+        */
+#ifdef HAVE_CRYPT_R
+       hash = crypt_r((char *)io->n.cleartext_utf8->data, cmd, &crypt_data);
+#else
+       /*
+        * No crypt_r falling back to crypt, which is NOT thread safe
+        * Thread safety MT-Unsafe race:crypt
+        */
+       hash = crypt((char *)io->n.cleartext_utf8->data, cmd);
+#endif
+       if (hash == NULL) {
+               char buf[1024];
+               int err = strerror_r(errno, buf, sizeof(buf));
+               if (err != 0) {
+                       strlcpy(buf, "Unknown error", sizeof(buf)-1);
+               }
+               ldb_asprintf_errstring(
+                       ldb,
+                       "setup_primary_userPassword: generation of a %s "
+                       "password hash failed: (%s)",
+                       scheme,
+                       buf);
+               TALLOC_FREE(frame);
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       hash_blob = talloc_zero(ctx, DATA_BLOB);
+
+       if (hash_blob == NULL) {
+               TALLOC_FREE(frame);
+               return ldb_oom(ldb);
+       }
+
+       *hash_blob =  data_blob_talloc(hash_blob,
+                                      (const uint8_t *)hash,
+                                      strlen(hash));
+       if (hash_blob->data == NULL) {
+               TALLOC_FREE(frame);
+               return ldb_oom(ldb);
+       }
+       hash_value->value = hash_blob;
+       TALLOC_FREE(frame);
+       return LDB_SUCCESS;
+}
+
+/*
+ * Calculate the desired extra password hashes
+ */
+static int setup_primary_userPassword(
+       struct setup_password_fields_io *io,
+       const struct supplementalCredentialsBlob *old_scb,
+       struct package_PrimaryUserPasswordBlob *p_userPassword_b)
+{
+       struct ldb_context *ldb = ldb_module_get_ctx(io->ac->module);
+       TALLOC_CTX *frame = talloc_stackframe();
+       int i;
+       int ret;
+
+       /*
+        * Save the current nt_hash, use this to determine if the password
+        * has been changed by windows. Which will invalidate the userPassword
+        * hash. Note once NTLM-Strong-NOWTF becomes available it should be
+        * used in preference to the NT password hash
+        */
+       if (io->g.nt_hash == NULL) {
+               ldb_asprintf_errstring(ldb,
+                       "No NT Hash, unable to calculate userPassword hashes");
+                       return LDB_ERR_UNWILLING_TO_PERFORM;
+       }
+       p_userPassword_b->current_nt_hash = *io->g.nt_hash;
+
+       /*
+        * Determine the number of hashes
+        * Note: that currently there is no limit on the number of hashes
+        *       no checking is done on the number of schemes specified
+        *       or for uniqueness.
+        */
+       p_userPassword_b->num_hashes = 0;
+       for (i = 0; io->ac->userPassword_schemes[i]; i++) {
+               p_userPassword_b->num_hashes++;
+       }
+
+       p_userPassword_b->hashes
+               = talloc_array(io->ac,
+                              struct package_PrimaryUserPasswordValue,
+                              p_userPassword_b->num_hashes);
+       if (p_userPassword_b->hashes == NULL) {
+               TALLOC_FREE(frame);
+               return ldb_oom(ldb);
+       }
+
+       for (i = 0; io->ac->userPassword_schemes[i]; i++) {
+               ret = setup_primary_userPassword_hash(
+                       p_userPassword_b->hashes,
+                       io,
+                       io->ac->userPassword_schemes[i],
+                       &p_userPassword_b->hashes[i]);
+               if (ret != LDB_SUCCESS) {
+                       TALLOC_FREE(frame);
+                       return ret;
+               }
+       }
+       return LDB_SUCCESS;
+}
+
+
 static int setup_primary_samba_gpg(struct setup_password_fields_io *io,
                                   struct package_PrimarySambaGPGBlob *pgb)
 {
@@ -1491,11 +1661,23 @@ static int setup_primary_samba_gpg(struct setup_password_fields_io *io,
                gret = gpgme_get_key(ctx, key_id, &keys[ki], 0 /* public key */);
                if (gret != GPG_ERR_NO_ERROR) {
                        keys[ki] = NULL;
-                       ldb_debug(ldb, LDB_DEBUG_ERROR,
-                                 "%s:%s: ki[%zu] key_id[%s] gret[%u] %s\n",
-                                 __location__, __func__,
-                                 ki, key_id,
-                                 gret, gpgme_strerror(gret));
+                       if (gpg_err_source(gret) == GPG_ERR_SOURCE_GPGME
+                           && gpg_err_code(gret) == GPG_ERR_EOF) {
+                               ldb_debug(ldb, LDB_DEBUG_ERROR,
+                                         "Invalid "
+                                         "'password hash gpg key ids': "
+                                         "Public Key ID [%s] "
+                                         "not found in keyring\n",
+                                         key_id);
+
+                       } else {
+                               ldb_debug(ldb, LDB_DEBUG_ERROR,
+                                         "%s:%s: ki[%zu] key_id[%s] "
+                                         "gret[%u] %s\n",
+                                         __location__, __func__,
+                                         ki, key_id,
+                                         gret, gpgme_strerror(gret));
+                       }
                        for (kr = 0; keys[kr] != NULL; kr++) {
                                gpgme_key_release(keys[kr]);
                        }
@@ -1553,7 +1735,7 @@ static int setup_primary_samba_gpg(struct setup_password_fields_io *io,
 #endif /* else ENABLE_GPGME */
 }
 
-#define NUM_PACKAGES 5
+#define NUM_PACKAGES 6
 static int setup_supplemental_field(struct setup_password_fields_io *io)
 {
        struct ldb_context *ldb;
@@ -1561,7 +1743,8 @@ static int setup_supplemental_field(struct setup_password_fields_io *io)
        struct supplementalCredentialsBlob *old_scb = NULL;
        /*
         * Packages +
-        * (Kerberos-Newer-Keys, Kerberos, WDigest, CLEARTEXT, SambaGPG)
+        * ( Kerberos-Newer-Keys, Kerberos,
+        *   WDigest, CLEARTEXT, userPassword, SambaGPG)
         */
        uint32_t num_names = 0;
        const char *names[1+NUM_PACKAGES];
@@ -1611,6 +1794,7 @@ static int setup_supplemental_field(struct setup_password_fields_io *io)
         * Primary:Kerberos
         * Primary:WDigest
         * Primary:CLEARTEXT (optional)
+        * Primary:userPassword
         * Primary:SambaGPG (optional)
         *
         * And the 'Packages' package is insert before the last
@@ -1781,6 +1965,53 @@ static int setup_supplemental_field(struct setup_password_fields_io *io)
                num_packages++;
        }
 
+       if (io->ac->userPassword_schemes) {
+               /*
+                * setup 'Primary:userPassword' element
+                */
+               struct package_PrimaryUserPasswordBlob
+                       p_userPassword_b;
+               DATA_BLOB p_userPassword_b_blob;
+               char *p_userPassword_b_hexstr;
+
+               names[num_names++] = "userPassword";
+
+               ret = setup_primary_userPassword(io,
+                                                old_scb,
+                                                &p_userPassword_b);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
+               }
+
+               ndr_err = ndr_push_struct_blob(
+                       &p_userPassword_b_blob,
+                       io->ac,
+                       &p_userPassword_b,
+                       (ndr_push_flags_fn_t)
+                       ndr_push_package_PrimaryUserPasswordBlob);
+               if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
+                       NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
+                       ldb_asprintf_errstring(
+                               ldb,
+                               "setup_supplemental_field: failed to push "
+                               "package_PrimaryUserPasswordBlob: %s",
+                               nt_errstr(status));
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+               p_userPassword_b_hexstr
+                       = data_blob_hex_string_upper(
+                               io->ac,
+                               &p_userPassword_b_blob);
+               if (!p_userPassword_b_hexstr) {
+                       return ldb_oom(ldb);
+               }
+               pp->name     = "Primary:userPassword";
+               pp->reserved = 1;
+               pp->data     = p_userPassword_b_hexstr;
+               pp++;
+               num_packages++;
+       }
+
        /*
         * setup 'Primary:SambaGPG' element
         */
@@ -2013,7 +2244,7 @@ static int setup_last_set_field(struct setup_password_fields_io *io)
                if (!io->ac->update_password) {
                        break;
                }
-               /* fall through */
+               FALL_THROUGH;
        case UINT64_MAX:
                if (!io->ac->update_password &&
                    io->u.pwdLastSet != 0 &&
@@ -2299,12 +2530,19 @@ 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;
+       struct ldb_message *pso_msg = NULL;
        NTSTATUS status;
        int ret;
 
+       /* PSO search result is optional (NULL if no PSO applies) */
+       if (io->ac->pso_res != NULL) {
+               pso_msg = io->ac->pso_res->message;
+       }
+
        status = dsdb_update_bad_pwd_count(io->ac, ldb,
                                           io->ac->search_res->message,
                                           io->ac->dom_res->message,
+                                          pso_msg,
                                           &mod_msg);
        if (!NT_STATUS_IS_OK(status)) {
                goto done;
@@ -2663,6 +2901,7 @@ static int check_password_restrictions_and_log(struct setup_password_fields_io *
                }
                log_authentication_event(msg_ctx,
                                         lp_ctx,
+                                        NULL,
                                         &ui,
                                         status,
                                         domain_name,
@@ -2910,10 +3149,27 @@ static int setup_io(struct ph_context *ac,
                info_msg = client_msg;
        }
 
-       if (smb_krb5_init_context(ac,
+       ret = smb_krb5_init_context(ac,
                                  (struct loadparm_context *)ldb_get_opaque(ldb, "loadparm"),
-                                 &io->smb_krb5_context) != 0) {
-               return ldb_operr(ldb);
+                                 &io->smb_krb5_context);
+
+       if (ret != 0) {
+               /*
+                * In the special case of mit krb5.conf vs heimdal, the includedir
+                * statement causes ret == 22 (KRB5_CONFIG_BADFORMAT) to be returned.
+                * We look for this case so that we can give a more instructional
+                * message to the administrator.
+                */
+               if (ret == KRB5_CONFIG_BADFORMAT || ret == EINVAL) {
+                       ldb_asprintf_errstring(ldb, "Failed to setup krb5_context: %s - "
+                               "This could be due to an invalid krb5 configuration. "
+                               "Please check your system's krb5 configuration is correct.",
+                               error_message(ret));
+               } else {
+                       ldb_asprintf_errstring(ldb, "Failed to setup krb5_context: %s",
+                               error_message(ret));
+               }
+               return LDB_ERR_OPERATIONS_ERROR;
        }
 
        io->ac                          = ac;
@@ -2935,7 +3191,6 @@ static int setup_io(struct ph_context *ac,
                                                                      "sAMAccountName", NULL);
        io->u.user_principal_name       = ldb_msg_find_attr_as_string(info_msg,
                                                                      "userPrincipalName", NULL);
-       io->u.is_computer               = ldb_msg_check_string_attribute(info_msg, "objectClass", "computer");
 
        /* Ensure it has an objectSID too */
        io->u.account_sid = samdb_result_dom_sid(ac, info_msg, "objectSid");
@@ -2983,9 +3238,7 @@ static int setup_io(struct ph_context *ac,
 
        /* 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));
+       io->u.restrictions = !(io->u.userAccountControl & UF_TRUST_ACCOUNT_MASK);
 
        if (io->u.is_krbtgt) {
                io->u.restrictions = 0;
@@ -3284,7 +3537,35 @@ static int setup_io(struct ph_context *ac,
                /* 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
+               struct ldb_control *pav_ctrl = NULL;
+               struct dsdb_control_password_acl_validation *pav = NULL;
+
+               pav_ctrl = ldb_request_get_control(ac->req,
+                               DSDB_CONTROL_PASSWORD_ACL_VALIDATION_OID);
+               if (pav_ctrl != NULL) {
+                       pav = talloc_get_type_abort(pav_ctrl->data,
+                               struct dsdb_control_password_acl_validation);
+               }
+
+               if (pav == NULL && ac->update_password) {
+                       bool ok;
+
+                       /*
+                        * If the DSDB_CONTROL_PASSWORD_ACL_VALIDATION_OID
+                        * control is missing, we require system access!
+                        */
+                       ok = dsdb_module_am_system(ac->module);
+                       if (!ok) {
+                               return ldb_module_operr(ac->module);
+                       }
+               }
+
+               if (pav != NULL) {
+                       /*
+                        * We assume what the acl module has validated.
+                        */
+                       ac->pwd_reset = pav->pwd_reset;
+               } else if (io->og.cleartext_utf8 || io->og.cleartext_utf16
                    || io->og.nt_hash || io->og.lm_hash) {
                        /* If we have an old password specified then for sure it
                         * is a user "password change" */
@@ -3441,7 +3722,8 @@ static struct ph_context *ph_init_context(struct ldb_module *module,
        lp_ctx = talloc_get_type_abort(ldb_get_opaque(ldb, "loadparm"),
                                       struct loadparm_context);
        ac->gpg_key_ids = lpcfg_password_hash_gpg_key_ids(lp_ctx);
-
+       ac->userPassword_schemes
+               = lpcfg_password_hash_userpassword_schemes(lp_ctx);
        return ac;
 }
 
@@ -3564,12 +3846,200 @@ static int password_hash_mod_search_self(struct ph_context *ac);
 static int ph_mod_search_callback(struct ldb_request *req, struct ldb_reply *ares);
 static int password_hash_mod_do_mod(struct ph_context *ac);
 
+/*
+ * LDB callback handler for searching for a user's PSO. Once we have all the
+ * Password Settings that apply to the user, we can continue with the modify
+ * operation
+ */
+static int get_pso_data_callback(struct ldb_request *req,
+                                struct ldb_reply *ares)
+{
+       struct ldb_context *ldb = NULL;
+       struct ph_context *ac = NULL;
+       bool domain_complexity = true;
+       bool pso_complexity = true;
+       struct dsdb_user_pwd_settings *settings = NULL;
+       int ret = LDB_SUCCESS;
+
+       ac = talloc_get_type(req->context, struct ph_context);
+       ldb = ldb_module_get_ctx(ac->module);
+
+       if (!ares) {
+               ret = LDB_ERR_OPERATIONS_ERROR;
+               goto done;
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                      ares->response, ares->error);
+       }
+
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
+
+               /* check status was initialized by the domain query */
+               if (ac->status == NULL) {
+                       talloc_free(ares);
+                       ldb_set_errstring(ldb, "Uninitialized status");
+                       ret = LDB_ERR_OPERATIONS_ERROR;
+                       goto done;
+               }
+
+               /*
+                * use the PSO's values instead of the domain defaults (the PSO
+                * attributes should always exist, but use the domain default
+                * values as a fallback).
+                */
+               settings = &ac->status->domain_data;
+               settings->store_cleartext =
+                       ldb_msg_find_attr_as_bool(ares->message,
+                                                 "msDS-PasswordReversibleEncryptionEnabled",
+                                                 settings->store_cleartext);
+
+               settings->pwdHistoryLength =
+                       ldb_msg_find_attr_as_uint(ares->message,
+                                                 "msDS-PasswordHistoryLength",
+                                                 settings->pwdHistoryLength);
+               settings->maxPwdAge =
+                       ldb_msg_find_attr_as_int64(ares->message,
+                                                  "msDS-MaximumPasswordAge",
+                                                  settings->maxPwdAge);
+               settings->minPwdAge =
+                       ldb_msg_find_attr_as_int64(ares->message,
+                                                  "msDS-MinimumPasswordAge",
+                                                  settings->minPwdAge);
+               settings->minPwdLength =
+                       ldb_msg_find_attr_as_uint(ares->message,
+                                                 "msDS-MinimumPasswordLength",
+                                                 settings->minPwdLength);
+               domain_complexity =
+                       (settings->pwdProperties & DOMAIN_PASSWORD_COMPLEX);
+               pso_complexity =
+                       ldb_msg_find_attr_as_bool(ares->message,
+                                                 "msDS-PasswordComplexityEnabled",
+                                                  domain_complexity);
+
+               /* set or clear the complexity bit if required */
+               if (pso_complexity && !domain_complexity) {
+                       settings->pwdProperties |= DOMAIN_PASSWORD_COMPLEX;
+               } else if (domain_complexity && !pso_complexity) {
+                       settings->pwdProperties &= ~DOMAIN_PASSWORD_COMPLEX;
+               }
+
+               if (ac->pso_res != NULL) {
+                       DBG_ERR("Too many PSO results for %s",
+                               ldb_dn_get_linearized(ac->search_res->message->dn));
+                       talloc_free(ac->pso_res);
+               }
+
+               /* store the PSO result (we may need its lockout settings) */
+               ac->pso_res = talloc_steal(ac, ares);
+               ret = LDB_SUCCESS;
+               break;
+
+       case LDB_REPLY_REFERRAL:
+               /* ignore */
+               talloc_free(ares);
+               ret = LDB_SUCCESS;
+               break;
+
+       case LDB_REPLY_DONE:
+               talloc_free(ares);
+
+               /*
+                * perform the next step of the modify operation (this code
+                * shouldn't get called in the 'user add' case)
+                */
+               if (ac->req->operation == LDB_MODIFY) {
+                       ret = password_hash_mod_do_mod(ac);
+               } else {
+                       ret = LDB_ERR_OPERATIONS_ERROR;
+               }
+               break;
+       }
+
+done:
+       if (ret != LDB_SUCCESS) {
+               struct ldb_reply *new_ares;
+
+               new_ares = talloc_zero(ac->req, struct ldb_reply);
+               if (new_ares == NULL) {
+                       ldb_oom(ldb);
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                              LDB_ERR_OPERATIONS_ERROR);
+               }
+
+               new_ares->error = ret;
+               if ((ret != LDB_ERR_OPERATIONS_ERROR) && (ac->change_status)) {
+                       /* On success and trivial errors a status control is being
+                        * added (used for example by the "samdb_set_password" call) */
+                       ldb_reply_add_control(new_ares,
+                                             DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID,
+                                             false,
+                                             ac->status);
+               }
+
+               return ldb_module_done(ac->req, new_ares->controls,
+                                      new_ares->response, new_ares->error);
+       }
+
+       return LDB_SUCCESS;
+}
+
+/*
+ * Builds and returns a search request to lookup up the PSO that applies to
+ * the user in question. Returns NULL if no PSO applies, or could not be found
+ */
+static struct ldb_request * build_pso_data_request(struct ph_context *ac)
+{
+       /* attrs[] is returned from this function in
+          pso_req->op.search.attrs, so it must be static, as
+          otherwise the compiler can put it on the stack */
+       static const char * const attrs[] = { "msDS-PasswordComplexityEnabled",
+                                             "msDS-PasswordReversibleEncryptionEnabled",
+                                             "msDS-PasswordHistoryLength",
+                                             "msDS-MaximumPasswordAge",
+                                             "msDS-MinimumPasswordAge",
+                                             "msDS-MinimumPasswordLength",
+                                             "msDS-LockoutThreshold",
+                                             "msDS-LockoutObservationWindow",
+                                             NULL };
+       struct ldb_context *ldb = NULL;
+       struct ldb_request *pso_req = NULL;
+       struct ldb_dn *pso_dn = NULL;
+       TALLOC_CTX *mem_ctx = ac;
+       int ret;
+
+       ldb = ldb_module_get_ctx(ac->module);
+
+       /* if a PSO applies to the user, we need to lookup the PSO as well */
+       pso_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, ac->search_res->message,
+                                        "msDS-ResultantPSO");
+       if (pso_dn == NULL) {
+               return NULL;
+       }
+
+       ret = ldb_build_search_req(&pso_req, ldb, mem_ctx, pso_dn,
+                                  LDB_SCOPE_BASE, NULL, attrs, NULL,
+                                  ac, get_pso_data_callback,
+                                  ac->dom_req);
+
+       /* log errors, but continue with the default domain settings */
+       if (ret != LDB_SUCCESS) {
+               DBG_ERR("Error %d constructing PSO query for user %s", ret,
+                       ldb_dn_get_linearized(ac->search_res->message->dn));
+       }
+       LDB_REQ_SET_LOCATION(pso_req);
+       return pso_req;
+}
+
+
 static int get_domain_data_callback(struct ldb_request *req,
                                    struct ldb_reply *ares)
 {
        struct ldb_context *ldb;
        struct ph_context *ac;
        struct loadparm_context *lp_ctx;
+       struct ldb_request *pso_req = NULL;
        int ret = LDB_SUCCESS;
 
        ac = talloc_get_type(req->context, struct ph_context);
@@ -3660,7 +4130,20 @@ static int get_domain_data_callback(struct ldb_request *req,
                        break;
 
                case LDB_MODIFY:
-                       ret = password_hash_mod_do_mod(ac);
+
+                       /*
+                        * The user may have an optional PSO applied. If so,
+                        * query the PSO to get the Fine-Grained Password Policy
+                        * for the user, before we perform the modify
+                        */
+                       pso_req = build_pso_data_request(ac);
+                       if (pso_req != NULL) {
+                               ret = ldb_next_request(ac->module, pso_req);
+                       } else {
+
+                               /* no PSO, so we can perform the modify now */
+                               ret = password_hash_mod_do_mod(ac);
+                       }
                        break;
 
                default:
@@ -3736,10 +4219,7 @@ static int password_hash_needed(struct ldb_module *module,
        const struct ldb_message *msg = NULL;
        struct ph_context *ac = NULL;
        const char *passwordAttrs[] = {
-               "userPassword",
-               "clearTextPassword",
-               "unicodePwd",
-               "dBCSPwd",
+               DSDB_PASSWORD_ATTRIBUTES,
                NULL
        };
        const char **a = NULL;
@@ -3970,8 +4450,7 @@ static int password_hash_modify(struct ldb_module *module, struct ldb_request *r
 {
        struct ldb_context *ldb = ldb_module_get_ctx(module);
        struct ph_context *ac = NULL;
-       const char *passwordAttrs[] = { "userPassword", "clearTextPassword",
-               "unicodePwd", "dBCSPwd", NULL }, **l;
+       const char *passwordAttrs[] = {DSDB_PASSWORD_ATTRIBUTES, NULL}, **l;
        unsigned int del_attr_cnt, add_attr_cnt, rep_attr_cnt;
        struct ldb_message_element *passwordAttr;
        struct ldb_message *msg;
@@ -4017,25 +4496,26 @@ static int password_hash_modify(struct ldb_module *module, struct ldb_request *r
                }
 
                while ((passwordAttr = ldb_msg_find_element(msg, *l)) != NULL) {
-                       if (LDB_FLAG_MOD_TYPE(passwordAttr->flags) == LDB_FLAG_MOD_DELETE) {
+                       unsigned int mtype = LDB_FLAG_MOD_TYPE(passwordAttr->flags);
+                       unsigned int nvalues = passwordAttr->num_values;
+
+                       if (mtype == LDB_FLAG_MOD_DELETE) {
                                ++del_attr_cnt;
                        }
-                       if (LDB_FLAG_MOD_TYPE(passwordAttr->flags) == LDB_FLAG_MOD_ADD) {
+                       if (mtype == LDB_FLAG_MOD_ADD) {
                                ++add_attr_cnt;
                        }
-                       if (LDB_FLAG_MOD_TYPE(passwordAttr->flags) == LDB_FLAG_MOD_REPLACE) {
+                       if (mtype == LDB_FLAG_MOD_REPLACE) {
                                ++rep_attr_cnt;
                        }
-                       if ((passwordAttr->num_values != 1) &&
-                           (LDB_FLAG_MOD_TYPE(passwordAttr->flags) == LDB_FLAG_MOD_ADD)) {
+                       if ((nvalues != 1) && (mtype == 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)) {
+                       if ((nvalues > 1) && (mtype == LDB_FLAG_MOD_DELETE)) {
                                talloc_free(ac);
                                ldb_asprintf_errstring(ldb,
                                                       "'%s' attribute must have zero or one value(s) on delete operations!",
@@ -4221,6 +4701,7 @@ static int password_hash_mod_search_self(struct ph_context *ac)
        struct ldb_context *ldb;
        static const char * const attrs[] = { "objectClass",
                                              "userAccountControl",
+                                             "msDS-ResultantPSO",
                                              "msDS-User-Account-Control-Computed",
                                              "pwdLastSet",
                                              "sAMAccountName",