krb5-samba: interdomain trust uses different salt principal
[samba.git] / source4 / dsdb / samdb / ldb_modules / password_hash.c
index 515be2621eda014ec081262566403ed39eaf2324..5f5710330044bb4dc37b4a76bf08866a42b1fc1f 100644 (file)
@@ -35,6 +35,7 @@
 #include "includes.h"
 #include "ldb_module.h"
 #include "libcli/auth/libcli_auth.h"
+#include "libcli/security/dom_sid.h"
 #include "system/kerberos.h"
 #include "auth/kerberos/kerberos.h"
 #include "dsdb/samdb/samdb.h"
 #include "../lib/crypto/crypto.h"
 #include "param/param.h"
 #include "lib/krb5_wrap/krb5_samba.h"
+#include "auth/common_auth.h"
+#include "lib/messaging/messaging.h"
+
+#ifdef ENABLE_GPGME
+#undef class
+#include <gpgme.h>
+#endif
 
 /* If we have decided there is a reason to work on this request, then
  * setup all the password hash types correctly.
@@ -87,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;
@@ -94,6 +104,8 @@ struct ph_context {
        struct dsdb_control_password_change_status *status;
        struct dsdb_control_password_change *change;
 
+       const char **gpg_key_ids;
+
        bool pwd_reset;
        bool change_status;
        bool hash_values;
@@ -101,6 +113,9 @@ struct ph_context {
        bool update_password;
        bool update_lastset;
        bool pwd_last_set_bypass;
+       bool pwd_last_set_default;
+       bool smartcard_reset;
+       const char **userPassword_schemes;
 };
 
 
@@ -109,14 +124,15 @@ struct setup_password_fields_io {
 
        struct smb_krb5_context *smb_krb5_context;
 
-       /* infos about the user account */
+       /* info about the user account */
        struct {
                uint32_t userAccountControl;
                NTTIME pwdLastSet;
                const char *sAMAccountName;
                const char *user_principal_name;
-               bool is_computer;
+               bool is_krbtgt;
                uint32_t restrictions;
+               struct dom_sid *account_sid;
        } u;
 
        /* new credentials and old given credentials */
@@ -157,6 +173,12 @@ struct setup_password_fields_io {
        } g;
 };
 
+static int msg_find_old_and_new_pwd_val(const struct ldb_message *msg,
+                                       const char *name,
+                                       enum ldb_request_type operation,
+                                       const struct ldb_val **new_val,
+                                       const struct ldb_val **old_val);
+
 static int password_hash_bypass(struct ldb_module *module, struct ldb_request *request)
 {
        struct ldb_context *ldb = ldb_module_get_ctx(module);
@@ -650,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: "
@@ -725,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: "
@@ -736,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);
-       kerberos_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);
@@ -1100,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,
@@ -1208,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,
@@ -1397,58 +1376,394 @@ 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)
+{
+       struct ldb_context *ldb = ldb_module_get_ctx(io->ac->module);
+#ifdef ENABLE_GPGME
+       gpgme_error_t gret;
+       gpgme_ctx_t ctx = NULL;
+       size_t num_keys = str_list_length(io->ac->gpg_key_ids);
+       gpgme_key_t keys[num_keys+1];
+       size_t ki = 0;
+       size_t kr = 0;
+       gpgme_data_t plain_data = NULL;
+       gpgme_data_t crypt_data = NULL;
+       size_t crypt_length = 0;
+       char *crypt_mem = NULL;
+
+       gret = gpgme_new(&ctx);
+       if (gret != GPG_ERR_NO_ERROR) {
+               ldb_debug(ldb, LDB_DEBUG_ERROR,
+                         "%s:%s: gret[%u] %s\n",
+                         __location__, __func__,
+                         gret, gpgme_strerror(gret));
+               return ldb_module_operr(io->ac->module);
+       }
+
+       gpgme_set_armor(ctx, 1);
+
+       gret = gpgme_data_new_from_mem(&plain_data,
+                                      (const char *)io->n.cleartext_utf16->data,
+                                      io->n.cleartext_utf16->length,
+                                      0 /* no copy */);
+       if (gret != GPG_ERR_NO_ERROR) {
+               ldb_debug(ldb, LDB_DEBUG_ERROR,
+                         "%s:%s: gret[%u] %s\n",
+                         __location__, __func__,
+                         gret, gpgme_strerror(gret));
+               gpgme_release(ctx);
+               return ldb_module_operr(io->ac->module);
+       }
+       gret = gpgme_data_new(&crypt_data);
+       if (gret != GPG_ERR_NO_ERROR) {
+               ldb_debug(ldb, LDB_DEBUG_ERROR,
+                         "%s:%s: gret[%u] %s\n",
+                         __location__, __func__,
+                         gret, gpgme_strerror(gret));
+               gpgme_data_release(plain_data);
+               gpgme_release(ctx);
+               return ldb_module_operr(io->ac->module);
+       }
+
+       for (ki = 0; ki < num_keys; ki++) {
+               const char *key_id = io->ac->gpg_key_ids[ki];
+               size_t len = strlen(key_id);
+
+               keys[ki] = NULL;
+
+               if (len < 16) {
+                       ldb_debug(ldb, LDB_DEBUG_FATAL,
+                                 "%s:%s: ki[%zu] key_id[%s] strlen < 16, "
+                                 "please specify at least the 64bit key id\n",
+                                 __location__, __func__,
+                                 ki, key_id);
+                       for (kr = 0; keys[kr] != NULL; kr++) {
+                               gpgme_key_release(keys[kr]);
+                       }
+                       gpgme_data_release(crypt_data);
+                       gpgme_data_release(plain_data);
+                       gpgme_release(ctx);
+                       return ldb_module_operr(io->ac->module);
+               }
+
+               gret = gpgme_get_key(ctx, key_id, &keys[ki], 0 /* public key */);
+               if (gret != GPG_ERR_NO_ERROR) {
+                       keys[ki] = NULL;
+                       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]);
+                       }
+                       gpgme_data_release(crypt_data);
+                       gpgme_data_release(plain_data);
+                       gpgme_release(ctx);
+                       return ldb_module_operr(io->ac->module);
+               }
+       }
+       keys[ki] = NULL;
+
+       gret = gpgme_op_encrypt(ctx, keys,
+                               GPGME_ENCRYPT_ALWAYS_TRUST,
+                               plain_data, crypt_data);
+       gpgme_data_release(plain_data);
+       plain_data = NULL;
+       for (kr = 0; keys[kr] != NULL; kr++) {
+               gpgme_key_release(keys[kr]);
+               keys[kr] = NULL;
+       }
+       gpgme_release(ctx);
+       ctx = NULL;
+       if (gret != GPG_ERR_NO_ERROR) {
+               ldb_debug(ldb, LDB_DEBUG_ERROR,
+                         "%s:%s: gret[%u] %s\n",
+                         __location__, __func__,
+                         gret, gpgme_strerror(gret));
+               gpgme_data_release(crypt_data);
+               return ldb_module_operr(io->ac->module);
+       }
+
+       crypt_mem = gpgme_data_release_and_get_mem(crypt_data, &crypt_length);
+       crypt_data = NULL;
+       if (crypt_mem == NULL) {
+               return ldb_module_oom(io->ac->module);
+       }
+
+       pgb->gpg_blob = data_blob_talloc(io->ac,
+                                        (const uint8_t *)crypt_mem,
+                                        crypt_length);
+       gpgme_free(crypt_mem);
+       crypt_mem = NULL;
+       crypt_length = 0;
+       if (pgb->gpg_blob.data == NULL) {
+               return ldb_module_oom(io->ac->module);
+       }
+
+       return LDB_SUCCESS;
+#else /* ENABLE_GPGME */
+       ldb_debug_set(ldb, LDB_DEBUG_FATAL,
+                     "You configured 'password hash gpg key ids', "
+                     "but GPGME support is missing. (%s:%d)",
+                     __FILE__, __LINE__);
+       return LDB_ERR_UNWILLING_TO_PERFORM;
+#endif /* else ENABLE_GPGME */
+}
+
+#define NUM_PACKAGES 6
 static int setup_supplemental_field(struct setup_password_fields_io *io)
 {
        struct ldb_context *ldb;
        struct supplementalCredentialsBlob scb;
        struct supplementalCredentialsBlob *old_scb = NULL;
-       /* Packages + (Kerberos-Newer-Keys, Kerberos, WDigest and CLEARTEXT) */
+       /*
+        * Packages +
+        * ( Kerberos-Newer-Keys, Kerberos,
+        *   WDigest, CLEARTEXT, userPassword, SambaGPG)
+        */
        uint32_t num_names = 0;
-       const char *names[1+4];
+       const char *names[1+NUM_PACKAGES];
        uint32_t num_packages = 0;
-       struct supplementalCredentialsPackage packages[1+4];
-       /* Packages */
-       struct supplementalCredentialsPackage *pp = NULL;
-       struct package_PackagesBlob pb;
-       DATA_BLOB pb_blob;
-       char *pb_hexstr;
-       /* Primary:Kerberos-Newer-Keys */
-       const char **nkn = NULL;
-       struct supplementalCredentialsPackage *pkn = NULL;
-       struct package_PrimaryKerberosBlob pknb;
-       DATA_BLOB pknb_blob;
-       char *pknb_hexstr;
-       /* Primary:Kerberos */
-       const char **nk = NULL;
-       struct supplementalCredentialsPackage *pk = NULL;
-       struct package_PrimaryKerberosBlob pkb;
-       DATA_BLOB pkb_blob;
-       char *pkb_hexstr;
-       /* Primary:WDigest */
-       const char **nd = NULL;
-       struct supplementalCredentialsPackage *pd = NULL;
-       struct package_PrimaryWDigestBlob pdb;
-       DATA_BLOB pdb_blob;
-       char *pdb_hexstr;
-       /* Primary:CLEARTEXT */
-       const char **nc = NULL;
-       struct supplementalCredentialsPackage *pc = NULL;
-       struct package_PrimaryCLEARTEXTBlob pcb;
-       DATA_BLOB pcb_blob;
-       char *pcb_hexstr;
+       struct supplementalCredentialsPackage packages[1+NUM_PACKAGES];
+       struct supplementalCredentialsPackage *pp = packages;
        int ret;
        enum ndr_err_code ndr_err;
-       uint8_t zero16[16];
        bool do_newer_keys = false;
        bool do_cleartext = false;
+       bool do_samba_gpg = false;
 
-       ZERO_STRUCT(zero16);
        ZERO_STRUCT(names);
+       ZERO_STRUCT(packages);
 
        ldb = ldb_module_get_ctx(io->ac->module);
 
        if (!io->n.cleartext_utf8) {
-               /* 
+               /*
                 * when we don't have a cleartext password
                 * we can't setup a supplementalCredential value
                 */
@@ -1469,12 +1784,8 @@ static int setup_supplemental_field(struct setup_password_fields_io *io)
                }
        }
        /* Per MS-SAMR 3.1.1.8.11.6 we create AES keys if our domain functionality level is 2008 or higher */
-       do_newer_keys = (dsdb_functional_level(ldb) >= DS_DOMAIN_FUNCTION_2008);
 
-       if (io->ac->status->domain_data.store_cleartext &&
-           (io->u.userAccountControl & UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED)) {
-               do_cleartext = true;
-       }
+
 
        /*
         * The ordering is this
@@ -1483,195 +1794,332 @@ 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
         * other package.
+        *
+        * Note: it's important that Primary:SambaGPG is added as
+        * the last element. This is the indication that it matches
+        * the current password. When a password change happens on
+        * a Windows DC, it will keep the old Primary:SambaGPG value,
+        * but as the first element.
         */
+       do_newer_keys = (dsdb_functional_level(ldb) >= DS_DOMAIN_FUNCTION_2008);
        if (do_newer_keys) {
-               /* Primary:Kerberos-Newer-Keys */
-               nkn = &names[num_names++];
-               pkn = &packages[num_packages++];
-       }
+               struct package_PrimaryKerberosBlob pknb;
+               DATA_BLOB pknb_blob;
+               char *pknb_hexstr;
+               /*
+                * setup 'Primary:Kerberos-Newer-Keys' element
+                */
+               names[num_names++] = "Kerberos-Newer-Keys";
 
-       /* Primary:Kerberos */
-       nk = &names[num_names++];
-       pk = &packages[num_packages++];
+               ret = setup_primary_kerberos_newer(io, old_scb, &pknb);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
+               }
 
-       if (!do_cleartext) {
-               /* Packages */
-               pp = &packages[num_packages++];
+               ndr_err = ndr_push_struct_blob(
+                       &pknb_blob, io->ac,
+                       &pknb,
+                       (ndr_push_flags_fn_t)ndr_push_package_PrimaryKerberosBlob);
+               if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
+                       NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
+                       ldb_asprintf_errstring(
+                               ldb,
+                               "setup_supplemental_field: "
+                               "failed to push "
+                               "package_PrimaryKerberosNeverBlob: %s",
+                               nt_errstr(status));
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+               pknb_hexstr = data_blob_hex_string_upper(io->ac, &pknb_blob);
+               if (!pknb_hexstr) {
+                       return ldb_oom(ldb);
+               }
+               pp->name        = "Primary:Kerberos-Newer-Keys";
+               pp->reserved    = 1;
+               pp->data        = pknb_hexstr;
+               pp++;
+               num_packages++;
        }
 
-       /* Primary:WDigest */
-       nd = &names[num_names++];
-       pd = &packages[num_packages++];
+       {
+               /*
+                * setup 'Primary:Kerberos' element
+                */
+               /* Primary:Kerberos */
+               struct package_PrimaryKerberosBlob pkb;
+               DATA_BLOB pkb_blob;
+               char *pkb_hexstr;
+
+               names[num_names++] = "Kerberos";
 
-       if (do_cleartext) {
-               /* Packages */
-               pp = &packages[num_packages++];
+               ret = setup_primary_kerberos(io, old_scb, &pkb);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
+               }
 
-               /* Primary:CLEARTEXT */
-               nc = &names[num_names++];
-               pc = &packages[num_packages++];
+               ndr_err = ndr_push_struct_blob(
+                       &pkb_blob, io->ac,
+                       &pkb,
+                       (ndr_push_flags_fn_t)ndr_push_package_PrimaryKerberosBlob);
+               if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
+                       NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
+                       ldb_asprintf_errstring(
+                               ldb,
+                               "setup_supplemental_field: "
+                               "failed to push package_PrimaryKerberosBlob: %s",
+                               nt_errstr(status));
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+               pkb_hexstr = data_blob_hex_string_upper(io->ac, &pkb_blob);
+               if (!pkb_hexstr) {
+                       return ldb_oom(ldb);
+               }
+               pp->name        = "Primary:Kerberos";
+               pp->reserved    = 1;
+               pp->data        = pkb_hexstr;
+               pp++;
+               num_packages++;
        }
 
-       if (pkn) {
+       {
                /*
-                * setup 'Primary:Kerberos-Newer-Keys' element
+                * setup 'Primary:WDigest' element
                 */
-               *nkn = "Kerberos-Newer-Keys";
+               struct package_PrimaryWDigestBlob pdb;
+               DATA_BLOB pdb_blob;
+               char *pdb_hexstr;
 
-               ret = setup_primary_kerberos_newer(io, old_scb, &pknb);
+               names[num_names++] = "WDigest";
+
+               ret = setup_primary_wdigest(io, old_scb, &pdb);
                if (ret != LDB_SUCCESS) {
                        return ret;
                }
 
-               ndr_err = ndr_push_struct_blob(&pknb_blob, io->ac,
-                                              &pknb,
-                                              (ndr_push_flags_fn_t)ndr_push_package_PrimaryKerberosBlob);
+               ndr_err = ndr_push_struct_blob(
+                       &pdb_blob, io->ac,
+                       &pdb,
+                       (ndr_push_flags_fn_t)ndr_push_package_PrimaryWDigestBlob);
                if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
                        NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
-                       ldb_asprintf_errstring(ldb,
-                                              "setup_supplemental_field: "
-                                              "failed to push package_PrimaryKerberosNeverBlob: %s",
-                                              nt_errstr(status));
+                       ldb_asprintf_errstring(
+                               ldb,
+                               "setup_supplemental_field: "
+                               "failed to push package_PrimaryWDigestBlob: %s",
+                               nt_errstr(status));
                        return LDB_ERR_OPERATIONS_ERROR;
                }
-               pknb_hexstr = data_blob_hex_string_upper(io->ac, &pknb_blob);
-               if (!pknb_hexstr) {
+               pdb_hexstr = data_blob_hex_string_upper(io->ac, &pdb_blob);
+               if (!pdb_hexstr) {
                        return ldb_oom(ldb);
                }
-               pkn->name       = "Primary:Kerberos-Newer-Keys";
-               pkn->reserved   = 1;
-               pkn->data       = pknb_hexstr;
+               pp->name        = "Primary:WDigest";
+               pp->reserved    = 1;
+               pp->data        = pdb_hexstr;
+               pp++;
+               num_packages++;
        }
 
        /*
-        * setup 'Primary:Kerberos' element
+        * setup 'Primary:CLEARTEXT' element
         */
-       *nk = "Kerberos";
-
-       ret = setup_primary_kerberos(io, old_scb, &pkb);
-       if (ret != LDB_SUCCESS) {
-               return ret;
+       if (io->ac->status->domain_data.store_cleartext &&
+           (io->u.userAccountControl & UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED)) {
+               do_cleartext = true;
        }
+       if (do_cleartext) {
+               struct package_PrimaryCLEARTEXTBlob pcb;
+               DATA_BLOB pcb_blob;
+               char *pcb_hexstr;
 
-       ndr_err = ndr_push_struct_blob(&pkb_blob, io->ac, 
-                                      &pkb,
-                                      (ndr_push_flags_fn_t)ndr_push_package_PrimaryKerberosBlob);
-       if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
-               NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
-               ldb_asprintf_errstring(ldb,
-                                      "setup_supplemental_field: "
-                                      "failed to push package_PrimaryKerberosBlob: %s",
-                                      nt_errstr(status));
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-       pkb_hexstr = data_blob_hex_string_upper(io->ac, &pkb_blob);
-       if (!pkb_hexstr) {
-               return ldb_oom(ldb);
-       }
-       pk->name        = "Primary:Kerberos";
-       pk->reserved    = 1;
-       pk->data        = pkb_hexstr;
+               names[num_names++] = "CLEARTEXT";
 
-       /*
-        * setup 'Primary:WDigest' element
-        */
-       *nd = "WDigest";
+               pcb.cleartext   = *io->n.cleartext_utf16;
 
-       ret = setup_primary_wdigest(io, old_scb, &pdb);
-       if (ret != LDB_SUCCESS) {
-               return ret;
+               ndr_err = ndr_push_struct_blob(
+                       &pcb_blob, io->ac,
+                       &pcb,
+                       (ndr_push_flags_fn_t)ndr_push_package_PrimaryCLEARTEXTBlob);
+               if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
+                       NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
+                       ldb_asprintf_errstring(
+                               ldb,
+                               "setup_supplemental_field: "
+                               "failed to push package_PrimaryCLEARTEXTBlob: %s",
+                               nt_errstr(status));
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+               pcb_hexstr = data_blob_hex_string_upper(io->ac, &pcb_blob);
+               if (!pcb_hexstr) {
+                       return ldb_oom(ldb);
+               }
+               pp->name        = "Primary:CLEARTEXT";
+               pp->reserved    = 1;
+               pp->data        = pcb_hexstr;
+               pp++;
+               num_packages++;
        }
 
-       ndr_err = ndr_push_struct_blob(&pdb_blob, io->ac, 
-                                      &pdb,
-                                      (ndr_push_flags_fn_t)ndr_push_package_PrimaryWDigestBlob);
-       if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
-               NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
-               ldb_asprintf_errstring(ldb,
-                                      "setup_supplemental_field: "
-                                      "failed to push package_PrimaryWDigestBlob: %s",
-                                      nt_errstr(status));
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-       pdb_hexstr = data_blob_hex_string_upper(io->ac, &pdb_blob);
-       if (!pdb_hexstr) {
-               return ldb_oom(ldb);
+       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++;
        }
-       pd->name        = "Primary:WDigest";
-       pd->reserved    = 1;
-       pd->data        = pdb_hexstr;
 
        /*
-        * setup 'Primary:CLEARTEXT' element
+        * setup 'Primary:SambaGPG' element
         */
-       if (pc) {
-               *nc             = "CLEARTEXT";
+       if (io->ac->gpg_key_ids != NULL) {
+               do_samba_gpg = true;
+       }
+       if (do_samba_gpg) {
+               struct package_PrimarySambaGPGBlob pgb;
+               DATA_BLOB pgb_blob;
+               char *pgb_hexstr;
 
-               pcb.cleartext   = *io->n.cleartext_utf16;
+               names[num_names++] = "SambaGPG";
+
+               ret = setup_primary_samba_gpg(io, &pgb);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
+               }
 
-               ndr_err = ndr_push_struct_blob(&pcb_blob, io->ac, 
-                                              &pcb,
-                                              (ndr_push_flags_fn_t)ndr_push_package_PrimaryCLEARTEXTBlob);
+               ndr_err = ndr_push_struct_blob(&pgb_blob, io->ac, &pgb,
+                       (ndr_push_flags_fn_t)ndr_push_package_PrimarySambaGPGBlob);
                if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
                        NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
                        ldb_asprintf_errstring(ldb,
-                                              "setup_supplemental_field: "
-                                              "failed to push package_PrimaryCLEARTEXTBlob: %s",
-                                              nt_errstr(status));
+                                       "setup_supplemental_field: failed to "
+                                       "push package_PrimarySambaGPGBlob: %s",
+                                       nt_errstr(status));
                        return LDB_ERR_OPERATIONS_ERROR;
                }
-               pcb_hexstr = data_blob_hex_string_upper(io->ac, &pcb_blob);
-               if (!pcb_hexstr) {
+               pgb_hexstr = data_blob_hex_string_upper(io->ac, &pgb_blob);
+               if (!pgb_hexstr) {
                        return ldb_oom(ldb);
                }
-               pc->name        = "Primary:CLEARTEXT";
-               pc->reserved    = 1;
-               pc->data        = pcb_hexstr;
+               pp->name        = "Primary:SambaGPG";
+               pp->reserved    = 1;
+               pp->data        = pgb_hexstr;
+               pp++;
+               num_packages++;
        }
 
        /*
         * setup 'Packages' element
         */
-       pb.names = names;
-       ndr_err = ndr_push_struct_blob(&pb_blob, io->ac, 
-                                      &pb,
-                                      (ndr_push_flags_fn_t)ndr_push_package_PackagesBlob);
-       if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
-               NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
-               ldb_asprintf_errstring(ldb,
-                                      "setup_supplemental_field: "
-                                      "failed to push package_PackagesBlob: %s",
-                                      nt_errstr(status));
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-       pb_hexstr = data_blob_hex_string_upper(io->ac, &pb_blob);
-       if (!pb_hexstr) {
-               return ldb_oom(ldb);
+       {
+               struct package_PackagesBlob pb;
+               DATA_BLOB pb_blob;
+               char *pb_hexstr;
+
+               pb.names = names;
+               ndr_err = ndr_push_struct_blob(
+                       &pb_blob, io->ac,
+                       &pb,
+                       (ndr_push_flags_fn_t)ndr_push_package_PackagesBlob);
+               if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
+                       NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
+                       ldb_asprintf_errstring(
+                               ldb,
+                               "setup_supplemental_field: "
+                               "failed to push package_PackagesBlob: %s",
+                               nt_errstr(status));
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+               pb_hexstr = data_blob_hex_string_upper(io->ac, &pb_blob);
+               if (!pb_hexstr) {
+                       return ldb_oom(ldb);
+               }
+               pp->name        = "Packages";
+               pp->reserved    = 2;
+               pp->data        = pb_hexstr;
+               num_packages++;
+               /*
+                * We don't increment pp so it's pointing to the last package
+                */
        }
-       pp->name        = "Packages";
-       pp->reserved    = 2;
-       pp->data        = pb_hexstr;
 
        /*
         * setup 'supplementalCredentials' value
         */
-       ZERO_STRUCT(scb);
-       scb.sub.num_packages    = num_packages;
-       scb.sub.packages        = packages;
-
-       ndr_err = ndr_push_struct_blob(&io->g.supplemental, io->ac, 
-                                      &scb,
-                                      (ndr_push_flags_fn_t)ndr_push_supplementalCredentialsBlob);
-       if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
-               NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
-               ldb_asprintf_errstring(ldb,
-                                      "setup_supplemental_field: "
-                                      "failed to push supplementalCredentialsBlob: %s",
-                                      nt_errstr(status));
-               return LDB_ERR_OPERATIONS_ERROR;
+       {
+               /*
+                * The 'Packages' element needs to be the second last element
+                * in supplementalCredentials
+                */
+               struct supplementalCredentialsPackage temp;
+               struct supplementalCredentialsPackage *prev;
+
+               prev = pp-1;
+               temp = *prev;
+               *prev = *pp;
+               *pp = temp;
+
+               ZERO_STRUCT(scb);
+               scb.sub.signature       = SUPPLEMENTAL_CREDENTIALS_SIGNATURE;
+               scb.sub.num_packages    = num_packages;
+               scb.sub.packages        = packages;
+
+               ndr_err = ndr_push_struct_blob(
+                       &io->g.supplemental, io->ac,
+                       &scb,
+                       (ndr_push_flags_fn_t)ndr_push_supplementalCredentialsBlob);
+               if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
+                       NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
+                       ldb_asprintf_errstring(
+                               ldb,
+                               "setup_supplemental_field: "
+                               "failed to push supplementalCredentialsBlob: %s",
+                               nt_errstr(status));
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
        }
 
        return LDB_SUCCESS;
@@ -1679,8 +2127,12 @@ static int setup_supplemental_field(struct setup_password_fields_io *io)
 
 static int setup_last_set_field(struct setup_password_fields_io *io)
 {
+       struct ldb_context *ldb = ldb_module_get_ctx(io->ac->module);
        const struct ldb_message *msg = NULL;
        struct timeval tv = { .tv_sec = 0 };
+       const struct ldb_val *old_val = NULL;
+       const struct ldb_val *new_val = NULL;
+       int ret;
 
        switch (io->ac->req->operation) {
        case LDB_ADD:
@@ -1695,14 +2147,23 @@ static int setup_last_set_field(struct setup_password_fields_io *io)
        }
 
        if (io->ac->pwd_last_set_bypass) {
-               struct ldb_message_element *el;
+               struct ldb_message_element *el1 = NULL;
+               struct ldb_message_element *el2 = NULL;
 
                if (msg == NULL) {
                        return LDB_ERR_CONSTRAINT_VIOLATION;
                }
 
-               el = ldb_msg_find_element(msg, "pwdLastSet");
-               if (el == NULL) {
+               el1 = dsdb_get_single_valued_attr(msg, "pwdLastSet",
+                                                 io->ac->req->operation);
+               if (el1 == NULL) {
+                       return LDB_ERR_CONSTRAINT_VIOLATION;
+               }
+               el2 = ldb_msg_find_element(msg, "pwdLastSet");
+               if (el2 == NULL) {
+                       return LDB_ERR_CONSTRAINT_VIOLATION;
+               }
+               if (el1 != el2) {
                        return LDB_ERR_CONSTRAINT_VIOLATION;
                }
 
@@ -1710,9 +2171,119 @@ static int setup_last_set_field(struct setup_password_fields_io *io)
                return LDB_SUCCESS;
        }
 
-       /* set it as now */
-       GetTimeOfDay(&tv);
-       io->g.last_set = timeval_to_nttime(&tv);
+       ret = msg_find_old_and_new_pwd_val(msg, "pwdLastSet",
+                                          io->ac->req->operation,
+                                          &new_val, &old_val);
+       if (ret != LDB_SUCCESS) {
+               return ret;
+       }
+
+       if (old_val != NULL && new_val == NULL) {
+               ldb_set_errstring(ldb,
+                                 "'pwdLastSet' deletion is not allowed!");
+               return LDB_ERR_UNWILLING_TO_PERFORM;
+       }
+
+       io->g.last_set = UINT64_MAX;
+       if (new_val != NULL) {
+               struct ldb_message *tmp_msg = NULL;
+
+               tmp_msg = ldb_msg_new(io->ac);
+               if (tmp_msg == NULL) {
+                       return ldb_module_oom(io->ac->module);
+               }
+
+               if (old_val != NULL) {
+                       NTTIME old_last_set = 0;
+
+                       ret = ldb_msg_add_value(tmp_msg, "oldval",
+                                               old_val, NULL);
+                       if (ret != LDB_SUCCESS) {
+                               return ret;
+                       }
+
+                       old_last_set = samdb_result_nttime(tmp_msg,
+                                                          "oldval",
+                                                          1);
+                       if (io->u.pwdLastSet != old_last_set) {
+                               return dsdb_module_werror(io->ac->module,
+                                       LDB_ERR_NO_SUCH_ATTRIBUTE,
+                                       WERR_DS_CANT_REM_MISSING_ATT_VAL,
+                                       "setup_last_set_field: old pwdLastSet "
+                                       "value not found!");
+                       }
+               }
+
+               ret = ldb_msg_add_value(tmp_msg, "newval",
+                                       new_val, NULL);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
+               }
+
+               io->g.last_set = samdb_result_nttime(tmp_msg,
+                                                    "newval",
+                                                    1);
+       } else if (ldb_msg_find_element(msg, "pwdLastSet")) {
+               ldb_set_errstring(ldb,
+                                 "'pwdLastSet' deletion is not allowed!");
+               return LDB_ERR_UNWILLING_TO_PERFORM;
+       } else if (io->ac->smartcard_reset) {
+               /*
+                * adding UF_SMARTCARD_REQUIRED doesn't update
+                * pwdLastSet implicitly.
+                */
+               io->ac->update_lastset = false;
+       }
+
+       /* only 0 or -1 (0xFFFFFFFFFFFFFFFF) are allowed */
+       switch (io->g.last_set) {
+       case 0:
+               if (!io->ac->pwd_last_set_default) {
+                       break;
+               }
+               if (!io->ac->update_password) {
+                       break;
+               }
+               FALL_THROUGH;
+       case UINT64_MAX:
+               if (!io->ac->update_password &&
+                   io->u.pwdLastSet != 0 &&
+                   io->u.pwdLastSet != UINT64_MAX)
+               {
+                       /*
+                        * Just setting pwdLastSet to -1, while not changing
+                        * any password field has no effect if pwdLastSet
+                        * is already non-zero.
+                        */
+                       io->ac->update_lastset = false;
+                       break;
+               }
+               /* -1 means set it as now */
+               GetTimeOfDay(&tv);
+               io->g.last_set = timeval_to_nttime(&tv);
+               break;
+       default:
+               return dsdb_module_werror(io->ac->module,
+                                         LDB_ERR_OTHER,
+                                         WERR_INVALID_PARAMETER,
+                                         "setup_last_set_field: "
+                                         "pwdLastSet must be 0 or -1 only!");
+       }
+
+       if (io->ac->req->operation == LDB_ADD) {
+               /*
+                * We always need to store the value on add
+                * operations.
+                */
+               return LDB_SUCCESS;
+       }
+
+       if (io->g.last_set == io->u.pwdLastSet) {
+               /*
+                * Just setting pwdLastSet to 0, is no-op if it's already 0.
+                */
+               io->ac->update_lastset = false;
+       }
 
        return LDB_SUCCESS;
 }
@@ -1826,6 +2397,15 @@ static int setup_password_fields(struct setup_password_fields_io *io)
                                         struct loadparm_context);
        int ret;
 
+       ret = setup_last_set_field(io);
+       if (ret != LDB_SUCCESS) {
+               return ret;
+       }
+
+       if (!io->ac->update_password) {
+               return LDB_SUCCESS;
+       }
+
        /* transform the old password (for password changes) */
        ret = setup_given_passwords(io, &io->og);
        if (ret != LDB_SUCCESS) {
@@ -1865,24 +2445,104 @@ static int setup_password_fields(struct setup_password_fields_io *io)
                return ret;
        }
 
-       ret = setup_last_set_field(io);
-       if (ret != LDB_SUCCESS) {
-               return ret;
+       return LDB_SUCCESS;
+}
+
+static int setup_smartcard_reset(struct setup_password_fields_io *io)
+{
+       struct ldb_context *ldb = ldb_module_get_ctx(io->ac->module);
+       struct loadparm_context *lp_ctx = talloc_get_type(
+               ldb_get_opaque(ldb, "loadparm"), struct loadparm_context);
+       struct supplementalCredentialsBlob scb = { .__ndr_size = 0 };
+       enum ndr_err_code ndr_err;
+
+       if (!io->ac->smartcard_reset) {
+               return LDB_SUCCESS;
+       }
+
+       io->g.nt_hash = talloc(io->ac, struct samr_Password);
+       if (io->g.nt_hash == NULL) {
+               return ldb_module_oom(io->ac->module);
+       }
+       generate_secret_buffer(io->g.nt_hash->hash,
+                              sizeof(io->g.nt_hash->hash));
+       io->g.nt_history_len = 0;
+
+       if (lpcfg_lanman_auth(lp_ctx)) {
+               io->g.lm_hash = talloc(io->ac, struct samr_Password);
+               if (io->g.lm_hash == NULL) {
+                       return ldb_module_oom(io->ac->module);
+               }
+               generate_secret_buffer(io->g.lm_hash->hash,
+                                      sizeof(io->g.lm_hash->hash));
+       } else {
+               io->g.lm_hash = NULL;
+       }
+       io->g.lm_history_len = 0;
+
+       /*
+        * We take the "old" value and store it
+        * with num_packages = 0.
+        *
+        * On "add" we have scb.sub.signature == 0, which
+        * results in:
+        *
+        * [0000] 00 00 00 00 00 00 00 00   00 00 00 00 00
+        *
+        * On modify it's likely to be scb.sub.signature ==
+        * SUPPLEMENTAL_CREDENTIALS_SIGNATURE (0x0050), which results in
+        * something like:
+        *
+        * [0000] 00 00 00 00 62 00 00 00   00 00 00 00 20 00 20 00
+        * [0010] 20 00 20 00 20 00 20 00   20 00 20 00 20 00 20 00
+        * [0020] 20 00 20 00 20 00 20 00   20 00 20 00 20 00 20 00
+        * [0030] 20 00 20 00 20 00 20 00   20 00 20 00 20 00 20 00
+        * [0040] 20 00 20 00 20 00 20 00   20 00 20 00 20 00 20 00
+        * [0050] 20 00 20 00 20 00 20 00   20 00 20 00 20 00 20 00
+        * [0060] 20 00 20 00 20 00 20 00   20 00 20 00 50 00 00
+        *
+        * See https://bugzilla.samba.org/show_bug.cgi?id=11441
+        * and ndr_{push,pull}_supplementalCredentialsSubBlob().
+        */
+       scb = io->o.scb;
+       scb.sub.num_packages = 0;
+
+       /*
+        * setup 'supplementalCredentials' value without packages
+        */
+       ndr_err = ndr_push_struct_blob(&io->g.supplemental, io->ac,
+                                      &scb,
+                                      (ndr_push_flags_fn_t)ndr_push_supplementalCredentialsBlob);
+       if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
+               NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
+               ldb_asprintf_errstring(ldb,
+                                      "setup_smartcard_reset: "
+                                      "failed to push supplementalCredentialsBlob: %s",
+                                      nt_errstr(status));
+               return LDB_ERR_OPERATIONS_ERROR;
        }
 
+       io->ac->update_password = true;
        return LDB_SUCCESS;
 }
 
-static int make_error_and_update_badPwdCount(struct setup_password_fields_io *io)
+static int make_error_and_update_badPwdCount(struct setup_password_fields_io *io, WERROR *werror)
 {
        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;
@@ -1971,20 +2631,28 @@ static int make_error_and_update_badPwdCount(struct setup_password_fields_io *io
 
 done:
        ret = LDB_ERR_CONSTRAINT_VIOLATION;
+       *werror = WERR_INVALID_PASSWORD;
        ldb_asprintf_errstring(ldb,
                               "%08X: %s - check_password_restrictions: "
                               "The old password specified doesn't match!",
-                              W_ERROR_V(WERR_INVALID_PASSWORD),
+                              W_ERROR_V(*werror),
                               ldb_strerror(ret));
        return ret;
 }
 
-static int check_password_restrictions(struct setup_password_fields_io *io)
+static int check_password_restrictions(struct setup_password_fields_io *io, WERROR *werror)
 {
-       struct ldb_context *ldb;
+       struct ldb_context *ldb = ldb_module_get_ctx(io->ac->module);
        int ret;
+       struct loadparm_context *lp_ctx =
+               lp_ctx = talloc_get_type(ldb_get_opaque(ldb, "loadparm"),
+                                        struct loadparm_context);
 
-       ldb = ldb_module_get_ctx(io->ac->module);
+       *werror = WERR_INVALID_PARAMETER;
+
+       if (!io->ac->update_password) {
+               return LDB_SUCCESS;
+       }
 
        /* First check the old password is correct, for password changes */
        if (!io->ac->pwd_reset) {
@@ -2003,7 +2671,7 @@ static int check_password_restrictions(struct setup_password_fields_io *io)
                   has no problems at all */
                if (io->og.nt_hash) {
                        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);
+                               return make_error_and_update_badPwdCount(io, werror);
                        }
 
                        nt_hash_checked = true;
@@ -2016,7 +2684,7 @@ static int check_password_restrictions(struct setup_password_fields_io *io)
                if (io->og.lm_hash) {
                        if ((!io->o.lm_hash && !nt_hash_checked)
                            || (io->o.lm_hash && memcmp(io->og.lm_hash->hash, io->o.lm_hash->hash, 16) != 0)) {
-                               return make_error_and_update_badPwdCount(io);
+                               return make_error_and_update_badPwdCount(io, werror);
                        }
                }
        }
@@ -2031,10 +2699,11 @@ static int check_password_restrictions(struct setup_password_fields_io *io)
            !io->ac->pwd_reset)
        {
                ret = LDB_ERR_CONSTRAINT_VIOLATION;
+               *werror = WERR_PASSWORD_RESTRICTION;
                ldb_asprintf_errstring(ldb,
                        "%08X: %s - check_password_restrictions: "
                        "password is too young to change!",
-                       W_ERROR_V(WERR_PASSWORD_RESTRICTION),
+                       W_ERROR_V(*werror),
                        ldb_strerror(ret));
                return ret;
        }
@@ -2046,7 +2715,8 @@ static int check_password_restrictions(struct setup_password_fields_io *io)
         */
        if (io->n.cleartext_utf8 != NULL) {
                enum samr_ValidationStatus vstat;
-               vstat = samdb_check_password(io->n.cleartext_utf8,
+               vstat = samdb_check_password(io->ac, lp_ctx,
+                                            io->n.cleartext_utf8,
                                             io->ac->status->domain_data.pwdProperties,
                                             io->ac->status->domain_data.minPwdLength);
                switch (vstat) {
@@ -2056,10 +2726,11 @@ static int check_password_restrictions(struct setup_password_fields_io *io)
 
                case SAMR_VALIDATION_STATUS_PWD_TOO_SHORT:
                        ret = LDB_ERR_CONSTRAINT_VIOLATION;
+                       *werror = WERR_PASSWORD_RESTRICTION;
                        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),
+                               W_ERROR_V(*werror),
                                ldb_strerror(ret),
                                io->ac->status->domain_data.minPwdLength);
                        io->ac->status->reject_reason = SAM_PWD_CHANGE_PASSWORD_TOO_SHORT;
@@ -2067,26 +2738,29 @@ static int check_password_restrictions(struct setup_password_fields_io *io)
 
                case SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH:
                        ret = LDB_ERR_CONSTRAINT_VIOLATION;
+                       *werror = WERR_PASSWORD_RESTRICTION;
                        ldb_asprintf_errstring(ldb,
                                "%08X: %s - check_password_restrictions: "
                                "the password does not meet the complexity criteria!",
-                               W_ERROR_V(WERR_PASSWORD_RESTRICTION),
+                               W_ERROR_V(*werror),
                                ldb_strerror(ret));
                        io->ac->status->reject_reason = SAM_PWD_CHANGE_NOT_COMPLEX;
                        return ret;
 
                default:
                        ret = LDB_ERR_CONSTRAINT_VIOLATION;
+                       *werror = WERR_PASSWORD_RESTRICTION;
                        ldb_asprintf_errstring(ldb,
                                "%08X: %s - check_password_restrictions: "
-                               "the password doesn't fit by a certain reason!",
-                               W_ERROR_V(WERR_PASSWORD_RESTRICTION),
+                               "the password doesn't fit due to a miscellaneous restriction!",
+                               W_ERROR_V(*werror),
                                ldb_strerror(ret));
                        return ret;
                }
        }
 
        if (io->ac->pwd_reset) {
+               *werror = WERR_OK;
                return LDB_SUCCESS;
        }
 
@@ -2098,10 +2772,11 @@ static int check_password_restrictions(struct setup_password_fields_io *io)
                        ret = memcmp(io->n.nt_hash, io->o.nt_history[i].hash, 16);
                        if (ret == 0) {
                                ret = LDB_ERR_CONSTRAINT_VIOLATION;
+                               *werror = WERR_PASSWORD_RESTRICTION;
                                ldb_asprintf_errstring(ldb,
                                        "%08X: %s - check_password_restrictions: "
                                        "the password was already used (in history)!",
-                                       W_ERROR_V(WERR_PASSWORD_RESTRICTION),
+                                       W_ERROR_V(*werror),
                                        ldb_strerror(ret));
                                io->ac->status->reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
                                return ret;
@@ -2117,10 +2792,11 @@ static int check_password_restrictions(struct setup_password_fields_io *io)
                        ret = memcmp(io->n.lm_hash, io->o.lm_history[i].hash, 16);
                        if (ret == 0) {
                                ret = LDB_ERR_CONSTRAINT_VIOLATION;
+                               *werror = WERR_PASSWORD_RESTRICTION;
                                ldb_asprintf_errstring(ldb,
                                        "%08X: %s - check_password_restrictions: "
                                        "the password was already used (in history)!",
-                                       W_ERROR_V(WERR_PASSWORD_RESTRICTION),
+                                       W_ERROR_V(*werror),
                                        ldb_strerror(ret));
                                io->ac->status->reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
                                return ret;
@@ -2131,10 +2807,11 @@ static int check_password_restrictions(struct setup_password_fields_io *io)
        /* are all password changes disallowed? */
        if (io->ac->status->domain_data.pwdProperties & DOMAIN_REFUSE_PASSWORD_CHANGE) {
                ret = LDB_ERR_CONSTRAINT_VIOLATION;
+               *werror = WERR_PASSWORD_RESTRICTION;
                ldb_asprintf_errstring(ldb,
                        "%08X: %s - check_password_restrictions: "
                        "password changes disabled!",
-                       W_ERROR_V(WERR_PASSWORD_RESTRICTION),
+                       W_ERROR_V(*werror),
                        ldb_strerror(ret));
                return ret;
        }
@@ -2142,10 +2819,11 @@ static int check_password_restrictions(struct setup_password_fields_io *io)
        /* can this user change the password? */
        if (io->u.userAccountControl & UF_PASSWD_CANT_CHANGE) {
                ret = LDB_ERR_CONSTRAINT_VIOLATION;
+               *werror = WERR_PASSWORD_RESTRICTION;
                ldb_asprintf_errstring(ldb,
                        "%08X: %s - check_password_restrictions: "
                        "password can't be changed on this account!",
-                       W_ERROR_V(WERR_PASSWORD_RESTRICTION),
+                       W_ERROR_V(*werror),
                        ldb_strerror(ret));
                return ret;
        }
@@ -2153,18 +2831,131 @@ static int check_password_restrictions(struct setup_password_fields_io *io)
        return LDB_SUCCESS;
 }
 
+static int check_password_restrictions_and_log(struct setup_password_fields_io *io)
+{
+       WERROR werror;
+       int ret = check_password_restrictions(io, &werror);
+       struct ph_context *ac = io->ac;
+       /*
+        * Password resets are not authentication events, and if the
+        * upper layer checked the password and supplied the hash
+        * values as proof, then this is also not an authentication
+        * even at this layer (already logged).  This is to log LDAP
+        * password changes.
+        */
+
+       /* Do not record a failure in the auth log below in the success case */
+       if (ret == LDB_SUCCESS) {
+               werror = WERR_OK;
+       }
+
+       if (ac->pwd_reset == false && ac->change == NULL) {
+               struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
+               struct imessaging_context *msg_ctx;
+               struct loadparm_context *lp_ctx
+                       = talloc_get_type_abort(ldb_get_opaque(ldb, "loadparm"),
+                                               struct loadparm_context);
+               NTSTATUS status = werror_to_ntstatus(werror);
+               const char *domain_name = lpcfg_sam_name(lp_ctx);
+               void *opaque_remote_address = NULL;
+               /*
+                * Forcing this via the NTLM auth structure is not ideal, but
+                * it is the most practical option right now, and ensures the
+                * logs are consistent, even if some elements are always NULL.
+                */
+               struct auth_usersupplied_info ui = {
+                       .mapped_state = true,
+                       .was_mapped = true,
+                       .client = {
+                               .account_name = io->u.sAMAccountName,
+                               .domain_name = domain_name,
+                       },
+                       .mapped = {
+                               .account_name = io->u.sAMAccountName,
+                               .domain_name = domain_name,
+                       },
+                       .service_description = "LDAP Password Change",
+                       .auth_description = "LDAP Modify",
+                       .password_type = "plaintext"
+               };
+
+               opaque_remote_address = ldb_get_opaque(ldb,
+                                                      "remoteAddress");
+               if (opaque_remote_address == NULL) {
+                       ldb_asprintf_errstring(ldb,
+                                              "Failed to obtain remote address for "
+                                              "the LDAP client while changing the "
+                                              "password");
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+               ui.remote_host = talloc_get_type(opaque_remote_address,
+                                                struct tsocket_address);
+
+               msg_ctx = imessaging_client_init(ac, lp_ctx,
+                                                ldb_get_event_context(ldb));
+               if (!msg_ctx) {
+                       ldb_asprintf_errstring(ldb,
+                                              "Failed to generate client messaging context in %s",
+                                              lpcfg_imessaging_path(ac, lp_ctx));
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+               log_authentication_event(msg_ctx,
+                                        lp_ctx,
+                                        NULL,
+                                        &ui,
+                                        status,
+                                        domain_name,
+                                        io->u.sAMAccountName,
+                                        NULL,
+                                        io->u.account_sid);
+
+       }
+       return ret;
+}
+
 static int update_final_msg(struct setup_password_fields_io *io)
 {
        struct ldb_context *ldb = ldb_module_get_ctx(io->ac->module);
        int ret;
        int el_flags = 0;
+       bool update_password = io->ac->update_password;
+       bool update_scb = io->ac->update_password;
+
+       /*
+        * If we add a user without initial password,
+        * we need to add replication meta data for
+        * following attributes:
+        * - unicodePwd
+        * - dBCSPwd
+        * - ntPwdHistory
+        * - lmPwdHistory
+        *
+        * If we add a user with initial password or a
+        * password is changed of an existing user,
+        * we need to replace the following attributes
+        * with a forced meta data update, e.g. also
+        * when updating an empty attribute with an empty value:
+        * - unicodePwd
+        * - dBCSPwd
+        * - ntPwdHistory
+        * - lmPwdHistory
+        * - supplementalCredentials
+        */
 
-       if (io->ac->req->operation == LDB_MODIFY) {
+       switch (io->ac->req->operation) {
+       case LDB_ADD:
+               update_password = true;
+               el_flags |= DSDB_FLAG_INTERNAL_FORCE_META_DATA;
+               break;
+       case LDB_MODIFY:
                el_flags |= LDB_FLAG_MOD_REPLACE;
+               el_flags |= DSDB_FLAG_INTERNAL_FORCE_META_DATA;
+               break;
+       default:
+               return ldb_module_operr(io->ac->module);
        }
 
-       /* make sure we replace all the old attributes */
-       if (io->ac->update_password && el_flags != 0) {
+       if (update_password) {
                ret = ldb_msg_add_empty(io->ac->update_msg,
                                        "unicodePwd",
                                        el_flags, NULL);
@@ -2189,6 +2980,8 @@ static int update_final_msg(struct setup_password_fields_io *io)
                if (ret != LDB_SUCCESS) {
                        return ret;
                }
+       }
+       if (update_scb) {
                ret = ldb_msg_add_empty(io->ac->update_msg,
                                        "supplementalCredentials",
                                        el_flags, NULL);
@@ -2196,7 +2989,7 @@ static int update_final_msg(struct setup_password_fields_io *io)
                        return ret;
                }
        }
-       if (io->ac->update_lastset && el_flags != 0) {
+       if (io->ac->update_lastset) {
                ret = ldb_msg_add_empty(io->ac->update_msg,
                                        "pwdLastSet",
                                        el_flags, NULL);
@@ -2251,12 +3044,14 @@ static int update_final_msg(struct setup_password_fields_io *io)
                        return ret;
                }
        }
-       ret = samdb_msg_add_uint64(ldb, io->ac,
-                                  io->ac->update_msg,
-                                  "pwdLastSet",
-                                  io->g.last_set);
-       if (ret != LDB_SUCCESS) {
-               return ret;
+       if (io->ac->update_lastset) {
+               ret = samdb_msg_add_uint64(ldb, io->ac,
+                                          io->ac->update_msg,
+                                          "pwdLastSet",
+                                          io->g.last_set);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
+               }
        }
 
        return LDB_SUCCESS;
@@ -2335,6 +3130,8 @@ static int setup_io(struct ph_context *ac,
                ldb_get_opaque(ldb, "loadparm"), struct loadparm_context);
        int ret;
        const struct ldb_message *info_msg = NULL;
+       struct dom_sid *account_sid = NULL;
+       int rodc_krbtgt = 0;
 
        ZERO_STRUCTP(io);
 
@@ -2352,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;
@@ -2366,14 +3180,37 @@ static int setup_io(struct ph_context *ac,
                /*
                 * We only take pwdLastSet from the existing object
                 * otherwise we leave it as 0.
+                *
+                * If no attribute is available, e.g. on deleted objects
+                * we remember that as UINT64_MAX.
                 */
-               io->u.pwdLastSet = samdb_result_nttime(info_msg, "pwdLastSet", 0);
+               io->u.pwdLastSet = samdb_result_nttime(info_msg, "pwdLastSet",
+                                                      UINT64_MAX);
        }
        io->u.sAMAccountName            = ldb_msg_find_attr_as_string(info_msg,
                                                                      "sAMAccountName", NULL);
        io->u.user_principal_name       = ldb_msg_find_attr_as_string(info_msg,
                                                                      "userPrincipalName", NULL);
-       io->u.is_computer               = ldb_msg_check_string_attribute(info_msg, "objectClass", "computer");
+
+       /* Ensure it has an objectSID too */
+       io->u.account_sid = samdb_result_dom_sid(ac, info_msg, "objectSid");
+       if (io->u.account_sid != NULL) {
+               NTSTATUS status;
+               uint32_t rid = 0;
+
+               status = dom_sid_split_rid(account_sid, io->u.account_sid, NULL, &rid);
+               if (NT_STATUS_IS_OK(status)) {
+                       if (rid == DOMAIN_RID_KRBTGT) {
+                               io->u.is_krbtgt = true;
+                       }
+               }
+       }
+
+       rodc_krbtgt = ldb_msg_find_attr_as_int(info_msg,
+                       "msDS-SecondaryKrbTgtNumber", 0);
+       if (rodc_krbtgt != 0) {
+               io->u.is_krbtgt = true;
+       }
 
        if (io->u.sAMAccountName == NULL) {
                ldb_asprintf_errstring(ldb,
@@ -2401,9 +3238,13 @@ 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;
+               io->ac->status->domain_data.pwdHistoryLength =
+                       MAX(io->ac->status->domain_data.pwdHistoryLength, 3);
+       }
 
        if (ac->userPassword) {
                ret = msg_find_old_and_new_pwd_val(client_msg, "userPassword",
@@ -2657,7 +3498,8 @@ static int setup_io(struct ph_context *ac,
        /* refuse the change if someone tries to set/change the password by
         * the lanman hash alone and we've deactivated that mechanism. This
         * would end in an account without any password! */
-       if ((!io->n.cleartext_utf8) && (!io->n.cleartext_utf16)
+       if (io->ac->update_password
+           && (!io->n.cleartext_utf8) && (!io->n.cleartext_utf16)
            && (!io->n.nt_hash) && (!io->n.lm_hash)) {
                ldb_asprintf_errstring(ldb,
                        "setup_io: "
@@ -2695,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" */
@@ -2709,6 +3579,59 @@ static int setup_io(struct ph_context *ac,
                return ldb_operr(ldb);
        }
 
+       if (io->u.is_krbtgt) {
+               size_t min = 196;
+               size_t max = 255;
+               size_t diff = max - min;
+               size_t len = max;
+               struct ldb_val *krbtgt_utf16 = NULL;
+
+               if (!ac->pwd_reset) {
+                       return dsdb_module_werror(ac->module,
+                                       LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS,
+                                       WERR_DS_ATT_ALREADY_EXISTS,
+                                       "Password change on krbtgt not permitted!");
+               }
+
+               if (io->n.cleartext_utf16 == NULL) {
+                       return dsdb_module_werror(ac->module,
+                                       LDB_ERR_UNWILLING_TO_PERFORM,
+                                       WERR_DS_INVALID_ATTRIBUTE_SYNTAX,
+                                       "Password reset on krbtgt requires UTF16!");
+               }
+
+               /*
+                * Instead of taking the callers value,
+                * we just generate a new random value here.
+                *
+                * Include null termination in the array.
+                */
+               if (diff > 0) {
+                       size_t tmp;
+
+                       generate_random_buffer((uint8_t *)&tmp, sizeof(tmp));
+
+                       tmp %= diff;
+
+                       len = min + tmp;
+               }
+
+               krbtgt_utf16 = talloc_zero(io->ac, struct ldb_val);
+               if (krbtgt_utf16 == NULL) {
+                       return ldb_oom(ldb);
+               }
+
+               *krbtgt_utf16 = data_blob_talloc_zero(krbtgt_utf16,
+                                                     (len+1)*2);
+               if (krbtgt_utf16->data == NULL) {
+                       return ldb_oom(ldb);
+               }
+               krbtgt_utf16->length = len * 2;
+               generate_secret_buffer(krbtgt_utf16->data,
+                                      krbtgt_utf16->length);
+               io->n.cleartext_utf16 = krbtgt_utf16;
+       }
+
        if (existing_msg != NULL) {
                NTSTATUS status;
 
@@ -2780,6 +3703,7 @@ static struct ph_context *ph_init_context(struct ldb_module *module,
 {
        struct ldb_context *ldb;
        struct ph_context *ac;
+       struct loadparm_context *lp_ctx = NULL;
 
        ldb = ldb_module_get_ctx(module);
 
@@ -2795,6 +3719,11 @@ static struct ph_context *ph_init_context(struct ldb_module *module,
        ac->update_password = update_password;
        ac->update_lastset = true;
 
+       lp_ctx = talloc_get_type_abort(ldb_get_opaque(ldb, "loadparm"),
+                                      struct loadparm_context);
+       ac->gpg_key_ids = lpcfg_password_hash_gpg_key_ids(lp_ctx);
+       ac->userPassword_schemes
+               = lpcfg_password_hash_userpassword_schemes(lp_ctx);
        return ac;
 }
 
@@ -2840,6 +3769,36 @@ static void ph_apply_controls(struct ph_context *ac)
                /* Mark the "bypass pwdLastSet" control as uncritical (done) */
                ctrl->critical = false;
        }
+
+       ac->pwd_last_set_default = false;
+       ctrl = ldb_request_get_control(ac->req,
+                               DSDB_CONTROL_PASSWORD_DEFAULT_LAST_SET_OID);
+       if (ctrl != NULL) {
+               ac->pwd_last_set_default = true;
+
+               /* Mark the "bypass pwdLastSet" control as uncritical (done) */
+               ctrl->critical = false;
+       }
+
+       ac->smartcard_reset = false;
+       ctrl = ldb_request_get_control(ac->req,
+                               DSDB_CONTROL_PASSWORD_USER_ACCOUNT_CONTROL_OID);
+       if (ctrl != NULL) {
+               struct dsdb_control_password_user_account_control *uac = NULL;
+               uint32_t added_flags = 0;
+
+               uac = talloc_get_type_abort(ctrl->data,
+                       struct dsdb_control_password_user_account_control);
+
+               added_flags = uac->new_flags & ~uac->old_flags;
+
+               if (added_flags & UF_SMARTCARD_REQUIRED) {
+                       ac->smartcard_reset = true;
+               }
+
+               /* Mark the "smartcard required" control as uncritical (done) */
+               ctrl->critical = false;
+       }
 }
 
 static int ph_op_callback(struct ldb_request *req, struct ldb_reply *ares)
@@ -2887,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);
@@ -2983,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:
@@ -3059,17 +4219,16 @@ 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;
        unsigned int attr_cnt = 0;
        struct ldb_control *bypass = NULL;
+       struct ldb_control *uac_ctrl = NULL;
        bool userPassword = dsdb_user_password_support(module, req, req);
        bool update_password = false;
+       bool processing_needed = false;
 
        *_ac = NULL;
 
@@ -3138,9 +4297,30 @@ static int password_hash_needed(struct ldb_module *module,
 
        if (attr_cnt > 0) {
                update_password = true;
+               processing_needed = true;
+       }
+
+       if (ldb_msg_find_element(msg, "pwdLastSet")) {
+               processing_needed = true;
+       }
+
+       uac_ctrl = ldb_request_get_control(req,
+                               DSDB_CONTROL_PASSWORD_USER_ACCOUNT_CONTROL_OID);
+       if (uac_ctrl != NULL) {
+               struct dsdb_control_password_user_account_control *uac = NULL;
+               uint32_t added_flags = 0;
+
+               uac = talloc_get_type_abort(uac_ctrl->data,
+                       struct dsdb_control_password_user_account_control);
+
+               added_flags = uac->new_flags & ~uac->old_flags;
+
+               if (added_flags & UF_SMARTCARD_REQUIRED) {
+                       processing_needed = true;
+               }
        }
 
-       if (!update_password) {
+       if (!processing_needed) {
                return ldb_next_request(module, req);
        }
 
@@ -3238,7 +4418,12 @@ static int password_hash_add_do_add(struct ph_context *ac)
                return ret;
        }
 
-       ret = check_password_restrictions(&io);
+       ret = check_password_restrictions_and_log(&io);
+       if (ret != LDB_SUCCESS) {
+               return ret;
+       }
+
+       ret = setup_smartcard_reset(&io);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
@@ -3265,12 +4450,12 @@ 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;
        struct ldb_request *down_req;
+       struct ldb_control *restore = NULL;
        int ret;
        unsigned int i = 0;
 
@@ -3311,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!",
@@ -3358,6 +4544,20 @@ static int password_hash_modify(struct ldb_module *module, struct ldb_request *r
                return LDB_ERR_UNWILLING_TO_PERFORM;
        }
 
+       restore = ldb_request_get_control(req,
+                                       DSDB_CONTROL_RESTORE_TOMBSTONE_OID);
+       if (restore == NULL) {
+               /*
+                * A tomstone reanimation generates a double update
+                * of pwdLastSet.
+                *
+                * So we only remove it without the
+                * DSDB_CONTROL_RESTORE_TOMBSTONE_OID control.
+                */
+               ldb_msg_remove_attr(msg, "pwdLastSet");
+       }
+
+
        /* if there was nothing else to be modified skip to next step */
        if (msg->num_elements == 0) {
                return password_hash_mod_search_self(ac);
@@ -3501,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",
@@ -3514,6 +4715,7 @@ static int password_hash_mod_search_self(struct ph_context *ac)
                                              "badPasswordTime",
                                              "badPwdCount",
                                              "lockoutTime",
+                                             "msDS-SecondaryKrbTgtNumber",
                                              NULL };
        struct ldb_request *search_req;
        int ret;
@@ -3555,7 +4757,12 @@ static int password_hash_mod_do_mod(struct ph_context *ac)
                return ret;
        }
 
-       ret = check_password_restrictions(&io);
+       ret = check_password_restrictions_and_log(&io);
+       if (ret != LDB_SUCCESS) {
+               return ret;
+       }
+
+       ret = setup_smartcard_reset(&io);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
@@ -3586,6 +4793,28 @@ static const struct ldb_module_ops ldb_password_hash_module_ops = {
 
 int ldb_password_hash_module_init(const char *version)
 {
+#ifdef ENABLE_GPGME
+       const char *gversion = NULL;
+#endif /* ENABLE_GPGME */
+
        LDB_MODULE_CHECK_VERSION(version);
+
+#ifdef ENABLE_GPGME
+       /*
+        * Note: this sets a SIGPIPE handler
+        * if none is active already. See:
+        * https://www.gnupg.org/documentation/manuals/gpgme/Signal-Handling.html#Signal-Handling
+        */
+       gversion = gpgme_check_version(GPGME_VERSION);
+       if (gversion == NULL) {
+               fprintf(stderr, "%s() in %s version[%s]: "
+                       "gpgme_check_version(%s) not available, "
+                       "gpgme_check_version(NULL) => '%s'\n",
+                       __func__, __FILE__, version,
+                       GPGME_VERSION, gpgme_check_version(NULL));
+               return LDB_ERR_UNAVAILABLE;
+       }
+#endif /* ENABLE_GPGME */
+
        return ldb_register_module(&ldb_password_hash_module_ops);
 }