s3-chgpasswd: split out a check_password_complexity() function.
[ira/wip.git] / source3 / smbd / chgpasswd.c
index 692e82680dbafad4978f173937a2966b73e5ea3e..2da36b2fe6cbeec82c59e49145e4fb8f5d7782ec 100644 (file)
@@ -2,11 +2,11 @@
    Unix SMB/CIFS implementation.
    Samba utility functions
    Copyright (C) Andrew Tridgell 1992-1998
-   Copyright (C) Andrew Bartlett 2001-2002
+   Copyright (C) Andrew Bartlett 2001-2004
    
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
-   the Free Software Foundation; either version 2 of the License, or
+   the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.
    
    This program is distributed in the hope that it will be useful,
    GNU General Public License for more details.
    
    You should have received a copy of the GNU General Public License
-   along with this program; if not, write to the Free Software
-   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
 
+/* These comments regard the code to change the user's unix password: */
+
 /* fork a child process to exec passwd and write to its
  * tty to change a users password. This is running as the
  * user who is attempting to change the password.
  */
 
-/* 
+/*
  * This code was copied/borrowed and stolen from various sources.
  * The primary source was the poppasswd.c from the authors of POPMail. This software
  * was included as a client to change passwords using the 'passwd' program
  * on the remote machine.
  *
- * This routine is called by set_user_password() in password.c only if ALLOW_PASSWORD_CHANGE
- * is defined in the compiler directives located in the Makefile.
- *
  * This code has been hacked by Bob Nance (nance@niehs.nih.gov) and Evan Patterson
  * (patters2@niehs.nih.gov) at the National Institute of Environmental Health Sciences
  * and rights to modify, distribute or incorporate this change to the CAP suite or
    */
 
 #include "includes.h"
-
-#ifdef HAVE_WORKING_CRACKLIB
-#include <crack.h>
-
-#ifndef HAVE_CRACKLIB_DICTPATH
-#ifndef CRACKLIB_DICTPATH
-#define CRACKLIB_DICTPATH SAMBA_CRACKLIB_DICTPATH
-#endif
-#endif
-#endif
-
-extern struct passdb_ops pdb_ops;
+#include "../libcli/auth/libcli_auth.h"
 
 static NTSTATUS check_oem_password(const char *user,
-                              uchar * lmdata, const uchar * lmhash,
-                              const uchar * ntdata, const uchar * nthash,
-                              SAM_ACCOUNT **hnd, char *new_passwd,
-                              int new_passwd_size);
+                                  uchar password_encrypted_with_lm_hash[516],
+                                  const uchar old_lm_hash_encrypted[16],
+                                  uchar password_encrypted_with_nt_hash[516],
+                                  const uchar old_nt_hash_encrypted[16],
+                                  struct samu *sampass,
+                                  char **pp_new_passwd);
 
 #if ALLOW_CHANGE_PASSWORD
 
 static int findpty(char **slave)
 {
-       int master;
-       static fstring line;
-       DIR *dirp;
+       int master = -1;
+       char *line = NULL;
+       SMB_STRUCT_DIR *dirp = NULL;
        const char *dpname;
 
+       *slave = NULL;
+
 #if defined(HAVE_GRANTPT)
        /* Try to open /dev/ptmx. If that fails, fall through to old method. */
-       if ((master = sys_open("/dev/ptmx", O_RDWR, 0)) >= 0)
-       {
+       if ((master = sys_open("/dev/ptmx", O_RDWR, 0)) >= 0) {
                grantpt(master);
                unlockpt(master);
-               *slave = (char *)ptsname(master);
-               if (*slave == NULL)
-               {
+               line = (char *)ptsname(master);
+               if (line) {
+                       *slave = SMB_STRDUP(line);
+               }
+
+               if (*slave == NULL) {
                        DEBUG(0,
                              ("findpty: Unable to create master/slave pty pair.\n"));
                        /* Stop fd leak on error. */
                        close(master);
                        return -1;
-               }
-               else
-               {
+               } else {
                        DEBUG(10,
                              ("findpty: Allocated slave pty %s\n", *slave));
                        return (master);
@@ -100,41 +91,46 @@ static int findpty(char **slave)
        }
 #endif /* HAVE_GRANTPT */
 
-       fstrcpy(line, "/dev/ptyXX");
+       line = SMB_STRDUP("/dev/ptyXX");
+       if (!line) {
+               return (-1);
+       }
 
-       dirp = opendir("/dev");
-       if (!dirp)
+       dirp = sys_opendir("/dev");
+       if (!dirp) {
+               SAFE_FREE(line);
                return (-1);
-       while ((dpname = readdirname(dirp)) != NULL)
-       {
-               if (strncmp(dpname, "pty", 3) == 0 && strlen(dpname) == 5)
-               {
+       }
+
+       while ((dpname = readdirname(dirp)) != NULL) {
+               if (strncmp(dpname, "pty", 3) == 0 && strlen(dpname) == 5) {
                        DEBUG(3,
                              ("pty: try to open %s, line was %s\n", dpname,
                               line));
                        line[8] = dpname[3];
                        line[9] = dpname[4];
-                       if ((master = sys_open(line, O_RDWR, 0)) >= 0)
-                       {
+                       if ((master = sys_open(line, O_RDWR, 0)) >= 0) {
                                DEBUG(3, ("pty: opened %s\n", line));
                                line[5] = 't';
                                *slave = line;
-                               closedir(dirp);
+                               sys_closedir(dirp);
                                return (master);
                        }
                }
        }
-       closedir(dirp);
+       sys_closedir(dirp);
+       SAFE_FREE(line);
        return (-1);
 }
 
 static int dochild(int master, const char *slavedev, const struct passwd *pass,
-                  const char *passwordprogram, BOOL as_root)
+                  const char *passwordprogram, bool as_root)
 {
        int slave;
        struct termios stermios;
        gid_t gid;
        uid_t uid;
+       char * const eptrs[1] = { NULL };
 
        if (pass == NULL)
        {
@@ -162,15 +158,24 @@ static int dochild(int master, const char *slavedev, const struct passwd *pass,
                DEBUG(3, ("More weirdness, could not open %s\n", slavedev));
                return (False);
        }
-#ifdef I_PUSH
-       ioctl(slave, I_PUSH, "ptem");
-       ioctl(slave, I_PUSH, "ldterm");
-#elif defined(TIOCSCTTY)
+#if defined(TIOCSCTTY) && !defined(SUNOS5)
+       /*
+        * On patched Solaris 10 TIOCSCTTY is defined but seems not to work,
+        * see the discussion under
+        * https://bugzilla.samba.org/show_bug.cgi?id=5366.
+        */
        if (ioctl(slave, TIOCSCTTY, 0) < 0)
        {
                DEBUG(3, ("Error in ioctl call for slave pty\n"));
                /* return(False); */
        }
+#elif defined(I_PUSH) && defined(I_FIND)
+       if (ioctl(slave, I_FIND, "ptem") == 0) {
+               ioctl(slave, I_PUSH, "ptem");
+       }
+       if (ioctl(slave, I_FIND, "ldterm") == 0) {
+               ioctl(slave, I_PUSH, "ldterm");
+       }
 #endif
 
        /* Close master. */
@@ -178,17 +183,17 @@ static int dochild(int master, const char *slavedev, const struct passwd *pass,
 
        /* Make slave stdin/out/err of child. */
 
-       if (sys_dup2(slave, STDIN_FILENO) != STDIN_FILENO)
+       if (dup2(slave, STDIN_FILENO) != STDIN_FILENO)
        {
                DEBUG(3, ("Could not re-direct stdin\n"));
                return (False);
        }
-       if (sys_dup2(slave, STDOUT_FILENO) != STDOUT_FILENO)
+       if (dup2(slave, STDOUT_FILENO) != STDOUT_FILENO)
        {
                DEBUG(3, ("Could not re-direct stdout\n"));
                return (False);
        }
-       if (sys_dup2(slave, STDERR_FILENO) != STDERR_FILENO)
+       if (dup2(slave, STDERR_FILENO) != STDERR_FILENO)
        {
                DEBUG(3, ("Could not re-direct stderr\n"));
                return (False);
@@ -227,7 +232,7 @@ static int dochild(int master, const char *slavedev, const struct passwd *pass,
               passwordprogram));
 
        /* execl() password-change application */
-       if (execl("/bin/sh", "sh", "-c", passwordprogram, NULL) < 0)
+       if (execle("/bin/sh", "sh", "-c", passwordprogram, NULL, eptrs) < 0)
        {
                DEBUG(3, ("Bad status returned from %s\n", passwordprogram));
                return (False);
@@ -237,17 +242,20 @@ static int dochild(int master, const char *slavedev, const struct passwd *pass,
 
 static int expect(int master, char *issue, char *expected)
 {
-       pstring buffer;
-       int attempts, timeout, nread, len;
-       BOOL match = False;
+       char buffer[1024];
+       int attempts, timeout, nread;
+       size_t len;
+       bool match = False;
 
        for (attempts = 0; attempts < 2; attempts++) {
+               NTSTATUS status;
                if (!strequal(issue, ".")) {
                        if (lp_passwd_chat_debug())
                                DEBUG(100, ("expect: sending [%s]\n", issue));
 
-                       if ((len = write(master, issue, strlen(issue))) != strlen(issue)) {
-                               DEBUG(2,("expect: (short) write returned %d\n", len ));
+                       if ((len = sys_write(master, issue, strlen(issue))) != strlen(issue)) {
+                               DEBUG(2,("expect: (short) write returned %d\n",
+                                        (int)len ));
                                return False;
                        }
                }
@@ -260,22 +268,32 @@ static int expect(int master, char *issue, char *expected)
                nread = 0;
                buffer[nread] = 0;
 
-               while ((len = read_socket_with_timeout(master, buffer + nread, 1,
-                                                      sizeof(buffer) - nread - 1,
-                                                      timeout)) > 0) {
+               while (True) {
+                       status = read_fd_with_timeout(
+                               master, buffer + nread, 1,
+                               sizeof(buffer) - nread - 1,
+                               timeout, &len);
+
+                       if (!NT_STATUS_IS_OK(status)) {
+                               break;
+                       }
                        nread += len;
                        buffer[nread] = 0;
 
                        {
                                /* Eat leading/trailing whitespace before match. */
-                               pstring str;
-                               pstrcpy( str, buffer);
-                               trim_char( str, ' ', ' ');
+                               char *str = SMB_STRDUP(buffer);
+                               if (!str) {
+                                       DEBUG(2,("expect: ENOMEM\n"));
+                                       return False;
+                               }
+                               trim_char(str, ' ', ' ');
 
-                               if ((match = (unix_wild_match(expected, str) == 0))) {
+                               if ((match = unix_wild_match(expected, str)) == True) {
                                        /* Now data has started to return, lower timeout. */
                                        timeout = lp_passwd_chat_timeout() * 100;
                                }
+                               SAFE_FREE(str);
                        }
                }
 
@@ -286,8 +304,8 @@ static int expect(int master, char *issue, char *expected)
                if (match)
                        break;
 
-               if (len < 0) {
-                       DEBUG(2, ("expect: %s\n", strerror(errno)));
+               if (!NT_STATUS_IS_OK(status)) {
+                       DEBUG(2, ("expect: %s\n", nt_errstr(status)));
                        return False;
                }
        }
@@ -306,45 +324,61 @@ static void pwd_sub(char *buf)
 
 static int talktochild(int master, const char *seq)
 {
+       TALLOC_CTX *frame = talloc_stackframe();
        int count = 0;
-       fstring issue, expected;
+       char *issue;
+       char *expected;
 
-       fstrcpy(issue, ".");
+       issue = talloc_strdup(frame, ".");
+       if (!issue) {
+               TALLOC_FREE(frame);
+               return false;
+       }
 
-       while (next_token(&seq, expected, NULL, sizeof(expected)))
-       {
+       while (next_token_talloc(frame, &seq, &expected, NULL)) {
                pwd_sub(expected);
                count++;
 
-               if (!expect(master, issue, expected))
-               {
+               if (!expect(master, issue, expected)) {
                        DEBUG(3, ("Response %d incorrect\n", count));
-                       return False;
+                       TALLOC_FREE(frame);
+                       return false;
                }
 
-               if (!next_token(&seq, issue, NULL, sizeof(issue)))
-                       fstrcpy(issue, ".");
-
+               if (!next_token_talloc(frame, &seq, &issue, NULL)) {
+                       issue = talloc_strdup(frame, ".");
+                       if (!issue) {
+                               TALLOC_FREE(frame);
+                               return false;
+                       }
+               }
                pwd_sub(issue);
        }
+
        if (!strequal(issue, ".")) {
                /* we have one final issue to send */
-               fstrcpy(expected, ".");
-               if (!expect(master, issue, expected))
+               expected = talloc_strdup(frame, ".");
+               if (!expected) {
+                       TALLOC_FREE(frame);
+                       return false;
+               }
+               if (!expect(master, issue, expected)) {
+                       TALLOC_FREE(frame);
                        return False;
+               }
        }
-
+       TALLOC_FREE(frame);
        return (count > 0);
 }
 
-static BOOL chat_with_program(char *passwordprogram, struct passwd *pass,
-                             char *chatsequence, BOOL as_root)
+static bool chat_with_program(char *passwordprogram, const struct passwd *pass,
+                             char *chatsequence, bool as_root)
 {
-       char *slavedev;
+       char *slavedev = NULL;
        int master;
        pid_t pid, wpid;
        int wstat;
-       BOOL chstat = False;
+       bool chstat = False;
 
        if (pass == NULL) {
                DEBUG(0, ("chat_with_program: user doesn't exist in the UNIX password database.\n"));
@@ -366,6 +400,7 @@ static BOOL chat_with_program(char *passwordprogram, struct passwd *pass,
 
        if ((pid = sys_fork()) < 0) {
                DEBUG(3, ("chat_with_program: Cannot fork() child for password change: %s\n", pass->pw_name));
+               SAFE_FREE(slavedev);
                close(master);
                CatchChild();
                return (False);
@@ -373,6 +408,9 @@ static BOOL chat_with_program(char *passwordprogram, struct passwd *pass,
 
        /* we now have a pty */
        if (pid > 0) {                  /* This is the parent process */
+               /* Don't need this anymore in parent. */
+               SAFE_FREE(slavedev);
+
                if ((chstat = talktochild(master, chatsequence)) == False) {
                        DEBUG(3, ("chat_with_program: Child failed to change password: %s\n", pass->pw_name));
                        kill(pid, SIGKILL);     /* be sure to end this process */
@@ -420,9 +458,10 @@ while we were waiting\n", WTERMSIG(wstat)));
                /* CHILD */
 
                /*
-                * Lose any oplock capabilities.
+                * Lose any elevated privileges.
                 */
-               oplock_set_capability(False, False);
+               drop_effective_capability(KERNEL_OPLOCK_CAPABILITY);
+               drop_effective_capability(DMAPI_ACCESS_CAPABILITY);
 
                /* make sure it doesn't freeze */
                alarm(20);
@@ -451,13 +490,14 @@ while we were waiting\n", WTERMSIG(wstat)));
        return (chstat);
 }
 
-BOOL chgpasswd(const char *name, const struct passwd *pass, 
-              const char *oldpass, const char *newpass, BOOL as_root)
+bool chgpasswd(const char *name, const struct passwd *pass,
+              const char *oldpass, const char *newpass, bool as_root)
 {
-       pstring passwordprogram;
-       pstring chatsequence;
+       char *passwordprogram = NULL;
+       char *chatsequence = NULL;
        size_t i;
        size_t len;
+       TALLOC_CTX *ctx = talloc_tos();
 
        if (!oldpass) {
                oldpass = "";
@@ -465,7 +505,7 @@ BOOL chgpasswd(const char *name, const struct passwd *pass,
 
        DEBUG(3, ("chgpasswd: Password change (as_root=%s) for user: %s\n", BOOLSTR(as_root), name));
 
-#if DEBUG_PASSWORD
+#ifdef DEBUG_PASSWORD
        DEBUG(100, ("chgpasswd: Passwords: old=%s new=%s\n", oldpass, newpass));
 #endif
 
@@ -478,7 +518,7 @@ BOOL chgpasswd(const char *name, const struct passwd *pass,
                return (False); /* inform the user */
        }
 
-       /* 
+       /*
         * Check the old and new passwords don't contain any control
         * characters.
         */
@@ -498,10 +538,13 @@ BOOL chgpasswd(const char *name, const struct passwd *pass,
                        return False;
                }
        }
-       
+
 #ifdef WITH_PAM
        if (lp_pam_password_change()) {
-               BOOL ret;
+               bool ret;
+#ifdef HAVE_SETLOCALE
+               const char *prevlocale = setlocale(LC_ALL, "C");
+#endif
 
                if (as_root)
                        become_root();
@@ -511,10 +554,14 @@ BOOL chgpasswd(const char *name, const struct passwd *pass,
                } else {
                        ret = smb_pam_passchange(name, oldpass, newpass);
                }
-                       
+
                if (as_root)
                        unbecome_root();
 
+#ifdef HAVE_SETLOCALE
+               setlocale(LC_ALL, prevlocale);
+#endif
+
                return ret;
        }
 #endif
@@ -523,49 +570,65 @@ BOOL chgpasswd(const char *name, const struct passwd *pass,
 
        if (pass == NULL) {
                DEBUG(0, ("chgpasswd: user %s doesn't exist in the UNIX password database.\n", name));
-               return False;
-       }
-
-       pstrcpy(passwordprogram, lp_passwd_program());
-       pstrcpy(chatsequence, lp_passwd_chat());
-
-       if (!*chatsequence) {
-               DEBUG(2, ("chgpasswd: Null chat sequence - no password changing\n"));
-               return (False);
+               return false;
        }
 
-       if (!*passwordprogram) {
+       passwordprogram = talloc_strdup(ctx, lp_passwd_program());
+       if (!passwordprogram || !*passwordprogram) {
                DEBUG(2, ("chgpasswd: Null password program - no password changing\n"));
-               return (False);
+               return false;
+       }
+       chatsequence = talloc_strdup(ctx, lp_passwd_chat());
+       if (!chatsequence || !*chatsequence) {
+               DEBUG(2, ("chgpasswd: Null chat sequence - no password changing\n"));
+               return false;
        }
 
        if (as_root) {
                /* The password program *must* contain the user name to work. Fail if not. */
-               if (strstr(passwordprogram, "%u") == NULL) {
+               if (strstr_m(passwordprogram, "%u") == NULL) {
                        DEBUG(0,("chgpasswd: Running as root the 'passwd program' parameter *MUST* contain \
 the string %%u, and the given string %s does not.\n", passwordprogram ));
-                       return False;
+                       return false;
                }
        }
 
-       pstring_sub(passwordprogram, "%u", name);
+       passwordprogram = talloc_string_sub(ctx, passwordprogram, "%u", name);
+       if (!passwordprogram) {
+               return false;
+       }
+
        /* note that we do NOT substitute the %o and %n in the password program
           as this would open up a security hole where the user could use
           a new password containing shell escape characters */
 
-       pstring_sub(chatsequence, "%u", name);
-       all_string_sub(chatsequence, "%o", oldpass, sizeof(pstring));
-       all_string_sub(chatsequence, "%n", newpass, sizeof(pstring));
-       return (chat_with_program
-               (passwordprogram, pass, chatsequence, as_root));
+       chatsequence = talloc_string_sub(ctx, chatsequence, "%u", name);
+       if (!chatsequence) {
+               return false;
+       }
+       chatsequence = talloc_all_string_sub(ctx,
+                                       chatsequence,
+                                       "%o",
+                                       oldpass);
+       if (!chatsequence) {
+               return false;
+       }
+       chatsequence = talloc_all_string_sub(ctx,
+                                       chatsequence,
+                                       "%n",
+                                       newpass);
+       return chat_with_program(passwordprogram,
+                               pass,
+                               chatsequence,
+                               as_root);
 }
 
 #else /* ALLOW_CHANGE_PASSWORD */
 
-BOOL chgpasswd(const char *name, const struct passwd *pass, 
-              const char *oldpass, const char *newpass, BOOL as_root)
+bool chgpasswd(const char *name, const struct passwd *pass, 
+              const char *oldpass, const char *newpass, bool as_root)
 {
-       DEBUG(0, ("chgpasswd: Password changing not compiled in (user=%s)\n", name));
+       DEBUG(0, ("chgpasswd: Unix Password changing not compiled in (user=%s)\n", name));
        return (False);
 }
 #endif /* ALLOW_CHANGE_PASSWORD */
@@ -574,15 +637,20 @@ BOOL chgpasswd(const char *name, const struct passwd *pass,
  Code to check the lanman hashed password.
 ************************************************************/
 
-BOOL check_lanman_password(char *user, uchar * pass1,
-                          uchar * pass2, SAM_ACCOUNT **hnd)
+bool check_lanman_password(char *user, uchar * pass1,
+                          uchar * pass2, struct samu **hnd)
 {
        uchar unenc_new_pw[16];
        uchar unenc_old_pw[16];
-       SAM_ACCOUNT *sampass = NULL;
-       uint16 acct_ctrl;
+       struct samu *sampass = NULL;
+       uint32 acct_ctrl;
        const uint8 *lanman_pw;
-       BOOL ret;
+       bool ret;
+
+       if ( !(sampass = samu_new(NULL)) ) {
+               DEBUG(0, ("samu_new() failed!\n"));
+               return False;
+       }
        
        become_root();
        ret = pdb_getsampwnam(sampass, user);
@@ -590,7 +658,7 @@ BOOL check_lanman_password(char *user, uchar * pass1,
 
        if (ret == False) {
                DEBUG(0,("check_lanman_password: getsampwnam returned NULL\n"));
-               pdb_free_sam(&sampass);
+               TALLOC_FREE(sampass);
                return False;
        }
        
@@ -599,7 +667,7 @@ BOOL check_lanman_password(char *user, uchar * pass1,
 
        if (acct_ctrl & ACB_DISABLED) {
                DEBUG(0,("check_lanman_password: account %s disabled.\n", user));
-               pdb_free_sam(&sampass);
+               TALLOC_FREE(sampass);
                return False;
        }
 
@@ -610,7 +678,7 @@ BOOL check_lanman_password(char *user, uchar * pass1,
                        return True;
                } else {
                        DEBUG(0, ("check_lanman_password: no lanman password !\n"));
-                       pdb_free_sam(&sampass);
+                       TALLOC_FREE(sampass);
                        return False;
                }
        }
@@ -624,7 +692,7 @@ BOOL check_lanman_password(char *user, uchar * pass1,
        /* Check that the two old passwords match. */
        if (memcmp(lanman_pw, unenc_old_pw, 16)) {
                DEBUG(0,("check_lanman_password: old password doesn't match.\n"));
-               pdb_free_sam(&sampass);
+               TALLOC_FREE(sampass);
                return False;
        }
 
@@ -641,12 +709,12 @@ BOOL check_lanman_password(char *user, uchar * pass1,
  is correct before calling. JRA.
 ************************************************************/
 
-BOOL change_lanman_password(SAM_ACCOUNT *sampass, uchar *pass2)
+bool change_lanman_password(struct samu *sampass, uchar *pass2)
 {
-       static uchar null_pw[16];
+       uchar null_pw[16];
        uchar unenc_new_pw[16];
-       BOOL ret;
-       uint16 acct_ctrl;
+       bool ret;
+       uint32 acct_ctrl;
        const uint8 *pwd;
 
        if (sampass == NULL) {
@@ -666,20 +734,21 @@ BOOL change_lanman_password(SAM_ACCOUNT *sampass, uchar *pass2)
        if (pwd == NULL) { 
                if (acct_ctrl & ACB_PWNOTREQ) {
                        uchar no_pw[14];
-                       memset(no_pw, '\0', 14);
+
+                       ZERO_STRUCT(no_pw);
+
                        E_P16(no_pw, null_pw);
 
-                       /* Get the new lanman hash. */
-                       D_P16(null_pw, pass2, unenc_new_pw);
+                       pwd = null_pw;
                } else {
                        DEBUG(0,("change_lanman_password: no lanman password !\n"));
                        return False;
                }
-       } else {
-               /* Get the new lanman hash. */
-               D_P16(pwd, pass2, unenc_new_pw);
        }
 
+       /* Get the new lanman hash. */
+       D_P16(pwd, pass2, unenc_new_pw);
+
        if (!pdb_set_lanman_passwd(sampass, unenc_new_pw, PDB_CHANGED)) {
                return False;
        }
@@ -688,14 +757,14 @@ BOOL change_lanman_password(SAM_ACCOUNT *sampass, uchar *pass2)
                return False;   /* We lose the NT hash. Sorry. */
        }
 
-       if (!pdb_set_pass_changed_now  (sampass)) {
-               pdb_free_sam(&sampass);
+       if (!pdb_set_pass_last_set_time  (sampass, time(NULL), PDB_CHANGED)) {
+               TALLOC_FREE(sampass);
                /* Not quite sure what this one qualifies as, but this will do */
-               return False; 
+               return False;
        }
+
        /* Now flush the sam_passwd struct to persistent storage */
-       ret = pdb_update_sam_account (sampass);
+       ret = NT_STATUS_IS_OK(pdb_update_sam_account (sampass));
 
        return ret;
 }
@@ -705,191 +774,340 @@ BOOL change_lanman_password(SAM_ACCOUNT *sampass, uchar *pass2)
 ************************************************************/
 
 NTSTATUS pass_oem_change(char *user,
-                        uchar * lmdata, uchar * lmhash,
-                        uchar * ntdata, uchar * nthash)
+                        uchar password_encrypted_with_lm_hash[516],
+                        const uchar old_lm_hash_encrypted[16],
+                        uchar password_encrypted_with_nt_hash[516],
+                        const uchar old_nt_hash_encrypted[16],
+                        enum samPwdChangeReason *reject_reason)
 {
-       fstring new_passwd;
-       SAM_ACCOUNT *sampass = NULL;
-       NTSTATUS nt_status = check_oem_password(user, lmdata, lmhash, ntdata, nthash,
-                                    &sampass, new_passwd, sizeof(new_passwd));
+       char *new_passwd = NULL;
+       struct samu *sampass = NULL;
+       NTSTATUS nt_status;
+       bool ret = false;
+
+       if (!(sampass = samu_new(NULL))) {
+               return NT_STATUS_NO_MEMORY;
+       }
+
+       become_root();
+       ret = pdb_getsampwnam(sampass, user);
+       unbecome_root();
 
-       if (!NT_STATUS_IS_OK(nt_status))
+       if (ret == false) {
+               DEBUG(0,("pass_oem_change: getsmbpwnam returned NULL\n"));
+               TALLOC_FREE(sampass);
+               return NT_STATUS_NO_SUCH_USER;
+       }
+
+       nt_status = check_oem_password(user,
+                                      password_encrypted_with_lm_hash,
+                                      old_lm_hash_encrypted,
+                                      password_encrypted_with_nt_hash,
+                                      old_nt_hash_encrypted,
+                                      sampass,
+                                      &new_passwd);
+
+       if (!NT_STATUS_IS_OK(nt_status)) {
+               TALLOC_FREE(sampass);
                return nt_status;
+       }
 
        /* We've already checked the old password here.... */
        become_root();
-       nt_status = change_oem_password(sampass, NULL, new_passwd, True);
+       nt_status = change_oem_password(sampass, NULL, new_passwd, True, reject_reason);
        unbecome_root();
 
-       memset(new_passwd, 0, sizeof(new_passwd));
+       memset(new_passwd, 0, strlen(new_passwd));
 
-       pdb_free_sam(&sampass);
+       TALLOC_FREE(sampass);
 
        return nt_status;
 }
 
 /***********************************************************
Code to check the OEM hashed password.
Decrypt and verify a user password change.
 
- this function ignores the 516 byte nt OEM hashed password
- but does use the lm OEM password to check the nt hashed-hash.
+ The 516 byte long buffers are encrypted with the old NT and
+ old LM passwords, and if the NT passwords are present, both
+ buffers contain a unicode string.
+
+ After decrypting the buffers, check the password is correct by
+ matching the old hashed passwords with the passwords in the passdb.
 
 ************************************************************/
 
 static NTSTATUS check_oem_password(const char *user,
-                              uchar * lmdata, const uchar * lmhash,
-                              const uchar * ntdata, const uchar * nthash,
-                              SAM_ACCOUNT **hnd, char *new_passwd,
-                              int new_passwd_size)
+                                  uchar password_encrypted_with_lm_hash[516],
+                                  const uchar old_lm_hash_encrypted[16],
+                                  uchar password_encrypted_with_nt_hash[516],
+                                  const uchar old_nt_hash_encrypted[16],
+                                  struct samu *sampass,
+                                  char **pp_new_passwd)
 {
-       static uchar null_pw[16];
-       static uchar null_ntpw[16];
-       SAM_ACCOUNT *sampass = NULL;
+       uchar null_pw[16];
+       uchar null_ntpw[16];
+       uint8 *password_encrypted;
+       const uint8 *encryption_key;
        const uint8 *lanman_pw, *nt_pw;
-       uint16 acct_ctrl;
-       int new_pw_len;
-       uchar new_ntp16[16];
-       uchar unenc_old_ntpw[16];
-       uchar new_p16[16];
-       uchar unenc_old_pw[16];
+       uint32 acct_ctrl;
+       size_t new_pw_len;
+       uchar new_nt_hash[16];
+       uchar new_lm_hash[16];
+       uchar verifier[16];
        char no_pw[2];
-       BOOL ret;
-
-       BOOL nt_pass_set = (ntdata != NULL && nthash != NULL);
-
-       *hnd = NULL;
-
-       pdb_init_sam(&sampass);
-
-       become_root();
-       ret = pdb_getsampwnam(sampass, user);
-       unbecome_root();
 
-       if (ret == False) {
-               DEBUG(0, ("check_oem_password: getsmbpwnam returned NULL\n"));
-               pdb_free_sam(&sampass);
-               return NT_STATUS_WRONG_PASSWORD;
-               /*
-                 TODO: check what Win2k returns for this:
-                 return NT_STATUS_NO_SUCH_USER; 
-               */
-       }
+       bool nt_pass_set = (password_encrypted_with_nt_hash && old_nt_hash_encrypted);
+       bool lm_pass_set = (password_encrypted_with_lm_hash && old_lm_hash_encrypted);
 
        acct_ctrl = pdb_get_acct_ctrl(sampass);
-       
+#if 0
+       /* I am convinced this check here is wrong, it is valid to
+        * change a password of a user that has a disabled account - gd */
+
        if (acct_ctrl & ACB_DISABLED) {
-               DEBUG(0,("check_lanman_password: account %s disabled.\n", user));
-               pdb_free_sam(&sampass);
+               DEBUG(2,("check_lanman_password: account %s disabled.\n", user));
                return NT_STATUS_ACCOUNT_DISABLED;
        }
+#endif
+       if ((acct_ctrl & ACB_PWNOTREQ) && lp_null_passwords()) {
+               /* construct a null password (in case one is needed */
+               no_pw[0] = 0;
+               no_pw[1] = 0;
+               nt_lm_owf_gen(no_pw, null_ntpw, null_pw);
+               lanman_pw = null_pw;
+               nt_pw = null_pw;
 
-       /* construct a null password (in case one is needed */
-       no_pw[0] = 0;
-       no_pw[1] = 0;
-       nt_lm_owf_gen(no_pw, null_ntpw, null_pw);
-
-       /* save pointers to passwords so we don't have to keep looking them up */
-       lanman_pw = pdb_get_lanman_passwd(sampass);
-       nt_pw = pdb_get_nt_passwd(sampass);
-
-       /* check for null passwords */
-       if (lanman_pw == NULL) {
-               if (!(acct_ctrl & ACB_PWNOTREQ)) {
-                       DEBUG(0,("check_oem_password: no lanman password !\n"));
-                       pdb_free_sam(&sampass);
-                       return NT_STATUS_WRONG_PASSWORD;
+       } else {
+               /* save pointers to passwords so we don't have to keep looking them up */
+               if (lp_lanman_auth()) {
+                       lanman_pw = pdb_get_lanman_passwd(sampass);
+               } else {
+                       lanman_pw = NULL;
                }
+               nt_pw = pdb_get_nt_passwd(sampass);
        }
-       
-       if (pdb_get_nt_passwd(sampass) == NULL && nt_pass_set) {
-               if (!(acct_ctrl & ACB_PWNOTREQ)) {
-                       DEBUG(0,("check_oem_password: no ntlm password !\n"));
-                       pdb_free_sam(&sampass);
-                       return NT_STATUS_WRONG_PASSWORD;
+
+       if (nt_pw && nt_pass_set) {
+               /* IDEAL Case: passwords are in unicode, and we can
+                * read use the password encrypted with the NT hash
+                */
+               password_encrypted = password_encrypted_with_nt_hash;
+               encryption_key = nt_pw;
+       } else if (lanman_pw && lm_pass_set) {
+               /* password may still be in unicode, but use LM hash version */
+               password_encrypted = password_encrypted_with_lm_hash;
+               encryption_key = lanman_pw;
+       } else if (nt_pass_set) {
+               DEBUG(1, ("NT password change supplied for user %s, but we have no NT password to check it with\n", 
+                         user));
+               return NT_STATUS_WRONG_PASSWORD;
+       } else if (lm_pass_set) {
+               if (lp_lanman_auth()) {
+                       DEBUG(1, ("LM password change supplied for user %s, but we have no LanMan password to check it with\n", 
+                                 user));
+               } else {
+                       DEBUG(1, ("LM password change supplied for user %s, but we have disabled LanMan authentication\n", 
+                                 user));
                }
+               return NT_STATUS_WRONG_PASSWORD;
+       } else {
+               DEBUG(1, ("password change requested for user %s, but no password supplied!\n", 
+                         user));
+               return NT_STATUS_WRONG_PASSWORD;
        }
-       
-       /* 
-        * Call the hash function to get the new password.
-        */
-       SamOEMhash( lmdata, lanman_pw, 516);
 
-       /* 
-        * The length of the new password is in the last 4 bytes of
-        * the data buffer.
+       /*
+        * Decrypt the password with the key
         */
+       arcfour_crypt( password_encrypted, encryption_key, 516);
 
-       new_pw_len = IVAL(lmdata, 512);
-
-       if (new_pw_len < 0 || new_pw_len > new_passwd_size - 1) {
-               DEBUG(0,("check_oem_password: incorrect password length (%d).\n", new_pw_len));
-               pdb_free_sam(&sampass);
+       if (!decode_pw_buffer(talloc_tos(),
+                               password_encrypted,
+                               pp_new_passwd,
+                               &new_pw_len,
+                               nt_pass_set ? CH_UTF16 : CH_DOS)) {
                return NT_STATUS_WRONG_PASSWORD;
        }
 
-       if (nt_pass_set) {
-               /*
-                * nt passwords are in unicode
-                */
-               pull_ucs2(NULL, new_passwd, 
-                         (const smb_ucs2_t *)&lmdata[512 - new_pw_len],
-                         new_passwd_size, new_pw_len, 0);
-       } else {
-               memcpy(new_passwd, &lmdata[512 - new_pw_len], new_pw_len);
-               new_passwd[new_pw_len] = 0;
-       }
-
        /*
         * To ensure we got the correct new password, hash it and
         * use it as a key to test the passed old password.
         */
 
-       nt_lm_owf_gen(new_passwd, new_ntp16, new_p16);
+       if (nt_pass_set) {
+               /* NT passwords, verify the NT hash. */
+
+               /* Calculate the MD4 hash (NT compatible) of the password */
+               memset(new_nt_hash, '\0', 16);
+               E_md4hash(*pp_new_passwd, new_nt_hash);
+
+               if (nt_pw) {
+                       /*
+                        * check the NT verifier
+                        */
+                       E_old_pw_hash(new_nt_hash, nt_pw, verifier);
+                       if (memcmp(verifier, old_nt_hash_encrypted, 16)) {
+                               DEBUG(0,("check_oem_password: old lm password doesn't match.\n"));
+                               return NT_STATUS_WRONG_PASSWORD;
+                       }
+
+                       /* We could check the LM password here, but there is
+                        * little point, we already know the password is
+                        * correct, and the LM password might not even be
+                        * present. */
+
+                       /* Further, LM hash generation algorithms
+                        * differ with charset, so we could
+                        * incorrectly fail a perfectly valid password
+                        * change */
+#ifdef DEBUG_PASSWORD
+                       DEBUG(100,
+                             ("check_oem_password: password %s ok\n", *pp_new_passwd));
+#endif
+                       return NT_STATUS_OK;
+               }
+
+               if (lanman_pw) {
+                       /*
+                        * check the lm verifier
+                        */
+                       E_old_pw_hash(new_nt_hash, lanman_pw, verifier);
+                       if (memcmp(verifier, old_lm_hash_encrypted, 16)) {
+                               DEBUG(0,("check_oem_password: old lm password doesn't match.\n"));
+                               return NT_STATUS_WRONG_PASSWORD;
+                       }
+#ifdef DEBUG_PASSWORD
+                       DEBUG(100,
+                             ("check_oem_password: password %s ok\n", *pp_new_passwd));
+#endif
+                       return NT_STATUS_OK;
+               }
+       }
+
+       if (lanman_pw && lm_pass_set) {
+
+               E_deshash(*pp_new_passwd, new_lm_hash);
 
-       if (!nt_pass_set) {
                /*
-                * Now use new_p16 as the key to see if the old
-                * password matches.
+                * check the lm verifier
                 */
-               D_P16(new_p16, lmhash, unenc_old_pw);
-
-               if (memcmp(lanman_pw, unenc_old_pw, 16)) {
+               E_old_pw_hash(new_lm_hash, lanman_pw, verifier);
+               if (memcmp(verifier, old_lm_hash_encrypted, 16)) {
                        DEBUG(0,("check_oem_password: old lm password doesn't match.\n"));
-                       pdb_free_sam(&sampass);
                        return NT_STATUS_WRONG_PASSWORD;
                }
 
 #ifdef DEBUG_PASSWORD
                DEBUG(100,
-                     ("check_oem_password: password %s ok\n", new_passwd));
+                     ("check_oem_password: password %s ok\n", *pp_new_passwd));
 #endif
-               *hnd = sampass;
                return NT_STATUS_OK;
        }
 
-       /*
-        * Now use new_p16 as the key to see if the old
-        * password matches.
-        */
-       D_P16(new_ntp16, lmhash, unenc_old_pw);
-       D_P16(new_ntp16, nthash, unenc_old_ntpw);
+       /* should not be reached */
+       return NT_STATUS_WRONG_PASSWORD;
+}
 
-       if (memcmp(lanman_pw, unenc_old_pw, 16)) {
-               DEBUG(0,("check_oem_password: old lm password doesn't match.\n"));
-               pdb_free_sam(&sampass);
-               return NT_STATUS_WRONG_PASSWORD;
+/***********************************************************
+ This routine takes the given password and checks it against
+ the password history. Returns True if this password has been
+ found in the history list.
+************************************************************/
+
+static bool check_passwd_history(struct samu *sampass, const char *plaintext)
+{
+       uchar new_nt_p16[NT_HASH_LEN];
+       uchar zero_md5_nt_pw[SALTED_MD5_HASH_LEN];
+       const uint8 *nt_pw;
+       const uint8 *pwhistory;
+       bool found = False;
+       int i;
+       uint32 pwHisLen, curr_pwHisLen;
+
+       pdb_get_account_policy(PDB_POLICY_PASSWORD_HISTORY, &pwHisLen);
+       if (pwHisLen == 0) {
+               return False;
        }
 
-       if (memcmp(nt_pw, unenc_old_ntpw, 16)) {
-               DEBUG(0,("check_oem_password: old nt password doesn't match.\n"));
-               pdb_free_sam(&sampass);
-               return NT_STATUS_WRONG_PASSWORD;
+       pwhistory = pdb_get_pw_history(sampass, &curr_pwHisLen);
+       if (!pwhistory || curr_pwHisLen == 0) {
+               return False;
+       }
+
+       /* Only examine the minimum of the current history len and
+          the stored history len. Avoids race conditions. */
+       pwHisLen = MIN(pwHisLen,curr_pwHisLen);
+
+       nt_pw = pdb_get_nt_passwd(sampass);
+
+       E_md4hash(plaintext, new_nt_p16);
+
+       if (!memcmp(nt_pw, new_nt_p16, NT_HASH_LEN)) {
+               DEBUG(10,("check_passwd_history: proposed new password for user %s is the same as the current password !\n",
+                       pdb_get_username(sampass) ));
+               return True;
+       }
+
+       dump_data(100, new_nt_p16, NT_HASH_LEN);
+       dump_data(100, pwhistory, PW_HISTORY_ENTRY_LEN*pwHisLen);
+
+       memset(zero_md5_nt_pw, '\0', SALTED_MD5_HASH_LEN);
+       for (i=0; i<pwHisLen; i++) {
+               uchar new_nt_pw_salted_md5_hash[SALTED_MD5_HASH_LEN];
+               const uchar *current_salt = &pwhistory[i*PW_HISTORY_ENTRY_LEN];
+               const uchar *old_nt_pw_salted_md5_hash = &pwhistory[(i*PW_HISTORY_ENTRY_LEN)+
+                                                       PW_HISTORY_SALT_LEN];
+               if (!memcmp(zero_md5_nt_pw, old_nt_pw_salted_md5_hash, SALTED_MD5_HASH_LEN)) {
+                       /* Ignore zero valued entries. */
+                       continue;
+               }
+               /* Create salted versions of new to compare. */
+               E_md5hash(current_salt, new_nt_p16, new_nt_pw_salted_md5_hash);
+
+               if (!memcmp(new_nt_pw_salted_md5_hash, old_nt_pw_salted_md5_hash, SALTED_MD5_HASH_LEN)) {
+                       DEBUG(1,("check_passwd_history: proposed new password for user %s found in history list !\n",
+                               pdb_get_username(sampass) ));
+                       found = True;
+                       break;
+               }
+       }
+       return found;
+}
+
+/***********************************************************
+************************************************************/
+
+NTSTATUS check_password_complexity(const char *username,
+                                  const char *password,
+                                  enum samPwdChangeReason *samr_reject_reason)
+{
+       TALLOC_CTX *tosctx = talloc_tos();
+
+       /* Use external script to check password complexity */
+       if (lp_check_password_script() && *(lp_check_password_script())) {
+               int check_ret;
+               char *cmd;
+
+               cmd = talloc_string_sub(tosctx, lp_check_password_script(), "%u", username);
+               if (!cmd) {
+                       return NT_STATUS_PASSWORD_RESTRICTION;
+               }
+
+               check_ret = smbrunsecret(cmd, password);
+               DEBUG(5,("check_password_complexity: check password script (%s) returned [%d]\n",
+                       cmd, check_ret));
+               TALLOC_FREE(cmd);
+
+               if (check_ret != 0) {
+                       DEBUG(1,("check_password_complexity: "
+                               "check password script said new password is not good enough!\n"));
+                       if (samr_reject_reason) {
+                               *samr_reject_reason = SAM_PWD_CHANGE_NOT_COMPLEX;
+                       }
+                       return NT_STATUS_PASSWORD_RESTRICTION;
+               }
        }
-#ifdef DEBUG_PASSWORD
-       DEBUG(100, ("check_oem_password: password %s ok\n", new_passwd));
-#endif
 
-       *hnd = sampass;
        return NT_STATUS_OK;
 }
 
@@ -900,78 +1118,85 @@ static NTSTATUS check_oem_password(const char *user,
  is correct before calling. JRA.
 ************************************************************/
 
-NTSTATUS change_oem_password(SAM_ACCOUNT *hnd, char *old_passwd, char *new_passwd, BOOL as_root)
+NTSTATUS change_oem_password(struct samu *hnd, char *old_passwd, char *new_passwd, bool as_root, enum samPwdChangeReason *samr_reject_reason)
 {
-       struct passwd *pass;
-
-       BOOL ret;
        uint32 min_len;
+       uint32 refuse;
+       TALLOC_CTX *tosctx = talloc_tos();
+       struct passwd *pass = NULL;
+       const char *username = pdb_get_username(hnd);
+       time_t can_change_time = pdb_get_pass_can_change_time(hnd);
+       NTSTATUS status;
+
+       if (samr_reject_reason) {
+               *samr_reject_reason = SAM_PWD_CHANGE_NO_ERROR;
+       }
 
-       if (time(NULL) < pdb_get_pass_can_change_time(hnd)) {
-               DEBUG(1, ("user %s cannot change password now, must wait until %s\n", 
-                         pdb_get_username(hnd), http_timestring(pdb_get_pass_can_change_time(hnd))));
-               return NT_STATUS_PASSWORD_RESTRICTION;
+       /* check to see if the secdesc has previously been set to disallow */
+       if (!pdb_get_pass_can_change(hnd)) {
+               DEBUG(1, ("user %s does not have permissions to change password\n", username));
+               if (samr_reject_reason) {
+                       *samr_reject_reason = SAM_PWD_CHANGE_NO_ERROR;
+               }
+               return NT_STATUS_ACCOUNT_RESTRICTION;
        }
 
-       if (account_policy_get(AP_MIN_PASSWORD_LEN, &min_len) && (strlen(new_passwd) < min_len)) {
+       /* check to see if it is a Machine account and if the policy
+        * denies machines to change the password. *
+        * Should we deny also SRVTRUST and/or DOMSTRUST ? .SSS. */
+       if (pdb_get_acct_ctrl(hnd) & ACB_WSTRUST) {
+               if (pdb_get_account_policy(PDB_POLICY_REFUSE_MACHINE_PW_CHANGE, &refuse) && refuse) {
+                       DEBUG(1, ("Machine %s cannot change password now, "
+                                 "denied by Refuse Machine Password Change policy\n",
+                                 username));
+                       if (samr_reject_reason) {
+                               *samr_reject_reason = SAM_PWD_CHANGE_NO_ERROR;
+                       }
+                       return NT_STATUS_ACCOUNT_RESTRICTION;
+               }
+       }
+
+       /* removed calculation here, becuase passdb now calculates
+          based on policy.  jmcd */
+       if ((can_change_time != 0) && (time(NULL) < can_change_time)) {
+               DEBUG(1, ("user %s cannot change password now, must "
+                         "wait until %s\n", username,
+                         http_timestring(tosctx, can_change_time)));
+               if (samr_reject_reason) {
+                       *samr_reject_reason = SAM_PWD_CHANGE_NO_ERROR;
+               }
+               return NT_STATUS_ACCOUNT_RESTRICTION;
+       }
+
+       if (pdb_get_account_policy(PDB_POLICY_MIN_PASSWORD_LEN, &min_len) && (str_charnum(new_passwd) < min_len)) {
                DEBUG(1, ("user %s cannot change password - password too short\n", 
-                         pdb_get_username(hnd)));
+                         username));
                DEBUGADD(1, (" account policy min password len = %d\n", min_len));
+               if (samr_reject_reason) {
+                       *samr_reject_reason = SAM_PWD_CHANGE_PASSWORD_TOO_SHORT;
+               }
                return NT_STATUS_PASSWORD_RESTRICTION;
 /*             return NT_STATUS_PWD_TOO_SHORT; */
        }
 
-       /* Take the passed information and test it for minimum criteria */
-       /* Minimum password length */
-       if (strlen(new_passwd) < lp_min_passwd_length()) {
-               /* too short, must be at least MINPASSWDLENGTH */
-               DEBUG(1, ("Password Change: user %s, New password is shorter than minimum password length = %d\n",
-                      pdb_get_username(hnd), lp_min_passwd_length()));
+       if (check_passwd_history(hnd,new_passwd)) {
+               if (samr_reject_reason) {
+                       *samr_reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
+               }
                return NT_STATUS_PASSWORD_RESTRICTION;
-/*             return NT_STATUS_PWD_TOO_SHORT; */
        }
 
-       pass = Get_Pwnam(pdb_get_username(hnd));
+       pass = Get_Pwnam_alloc(tosctx, username);
        if (!pass) {
-               DEBUG(1, ("check_oem_password: Username does not exist in system !?!\n"));
-       }
-
-#ifdef HAVE_WORKING_CRACKLIB
-       if (pass) {
-               /* if we can, become the user to overcome internal cracklib sillyness */
-               if (!push_sec_ctx())
-                       return NT_STATUS_UNSUCCESSFUL;
-               
-               set_sec_ctx(pass->pw_uid, pass->pw_gid, 0, NULL, NULL);
-               set_re_uid();
-       }
-
-       if (lp_use_cracklib()) {
-               const char *crack_check_reason;
-               DEBUG(4, ("change_oem_password: Checking password for user [%s]"
-                         " against cracklib. \n", pdb_get_username(hnd)));
-               DEBUGADD(4, ("If this is your last message, then something is "
-                            "wrong with cracklib, it might be missing it's "
-                            "dictionaries at %s\n", 
-                            CRACKLIB_DICTPATH));
-               dbgflush();
-
-               crack_check_reason = FascistCheck(new_passwd, (char *)CRACKLIB_DICTPATH);
-               if (crack_check_reason) {
-                       DEBUG(1, ("Password Change: user [%s], "
-                                 "New password failed cracklib test - %s\n",
-                         pdb_get_username(hnd), crack_check_reason));
-                       
-                       /* get back to where we should be */
-                       if (pass)
-                               pop_sec_ctx();
-                       return NT_STATUS_PASSWORD_RESTRICTION;
-               }
+               DEBUG(1, ("change_oem_password: Username %s does not exist in system !?!\n", username));
+               return NT_STATUS_ACCESS_DENIED;
        }
 
-       if (pass)
-               pop_sec_ctx();
-#endif
+       status = check_password_complexity(username, new_passwd, samr_reject_reason);
+       if (!NT_STATUS_IS_OK(status)) {
+               TALLOC_FREE(pass);
+               return status;
+       }
 
        /*
         * If unix password sync was requested, attempt to change
@@ -986,20 +1211,17 @@ NTSTATUS change_oem_password(SAM_ACCOUNT *hnd, char *old_passwd, char *new_passw
         */
        
        if(lp_unix_password_sync() &&
-               !chgpasswd(pdb_get_username(hnd), pass, old_passwd, new_passwd, as_root)) {
+               !chgpasswd(username, pass, old_passwd, new_passwd, as_root)) {
+               TALLOC_FREE(pass);
                return NT_STATUS_ACCESS_DENIED;
        }
 
+       TALLOC_FREE(pass);
+
        if (!pdb_set_plaintext_passwd (hnd, new_passwd)) {
                return NT_STATUS_ACCESS_DENIED;
        }
 
        /* Now write it into the file. */
-       ret = pdb_update_sam_account (hnd);
-
-       if (!ret) {
-               return NT_STATUS_ACCESS_DENIED;
-       }
-       
-       return NT_STATUS_OK;
+       return pdb_update_sam_account (hnd);
 }