rename public functions from winbind_client.h
[metze/old/v3-2-winbind-ndr.git] / source / nsswitch / pam_winbind.c
index 6929c3f3db0232279e19481ca7bb2125284ac203..f4793f77c8b1ec196a0d6f4ed507c00d3da743d4 100644 (file)
 
 #define _PAM_LOG_FUNCTION_ENTER(function, pamh, ctrl, flags) \
        do { \
-               _pam_log_debug(pamh, ctrl, LOG_DEBUG, "[pamh: 0x%08x] ENTER: " function " (flags: 0x%04x)", (uint32) pamh, flags); \
+               _pam_log_debug(pamh, ctrl, LOG_DEBUG, "[pamh: %p] ENTER: " function " (flags: 0x%04x)", pamh, flags); \
                _pam_log_state(pamh, ctrl); \
        } while (0)
 
 #define _PAM_LOG_FUNCTION_LEAVE(function, pamh, ctrl, retval) \
        do { \
-               _pam_log_debug(pamh, ctrl, LOG_DEBUG, "[pamh: 0x%08x] LEAVE: " function " returning %d", (uint32) pamh, retval); \
+               _pam_log_debug(pamh, ctrl, LOG_DEBUG, "[pamh: %p] LEAVE: " function " returning %d", pamh, retval); \
                _pam_log_state(pamh, ctrl); \
        } while (0)
 
@@ -73,11 +73,12 @@ static void _pam_log_int(const pam_handle_t *pamh, int err, const char *format,
 }
 #endif /* HAVE_PAM_VSYSLOG */
 
-static BOOL _pam_log_is_silent(int ctrl)
+static bool _pam_log_is_silent(int ctrl)
 {
        return on(ctrl, WINBIND_SILENT);
 }
 
+static void _pam_log(const pam_handle_t *pamh, int ctrl, int err, const char *format, ...) PRINTF_ATTRIBUTE(4,5);
 static void _pam_log(const pam_handle_t *pamh, int ctrl, int err, const char *format, ...)
 {
        va_list args;
@@ -91,32 +92,33 @@ static void _pam_log(const pam_handle_t *pamh, int ctrl, int err, const char *fo
        va_end(args);
 }
 
-static BOOL _pam_log_is_debug_enabled(int ctrl)
+static bool _pam_log_is_debug_enabled(int ctrl)
 {
        if (ctrl == -1) {
-               return False;
+               return false;
        }
 
        if (_pam_log_is_silent(ctrl)) {
-               return False;
+               return false;
        }
 
        if (!(ctrl & WINBIND_DEBUG_ARG)) {
-               return False;
+               return false;
        }
 
-       return True;
+       return true;
 }
 
-static BOOL _pam_log_is_debug_state_enabled(int ctrl)
+static bool _pam_log_is_debug_state_enabled(int ctrl)
 {
        if (!(ctrl & WINBIND_DEBUG_STATE)) {
-               return False;
+               return false;
        }
 
        return _pam_log_is_debug_enabled(ctrl);
 }
 
+static void _pam_log_debug(const pam_handle_t *pamh, int ctrl, int err, const char *format, ...) PRINTF_ATTRIBUTE(4,5);
 static void _pam_log_debug(const pam_handle_t *pamh, int ctrl, int err, const char *format, ...)
 {
        va_list args;
@@ -141,9 +143,9 @@ static void _pam_log_state_datum(const pam_handle_t *pamh, int ctrl, int item_ty
        if (data != NULL) {
                const char *type = (item_type != 0) ? "ITEM" : "DATA";
                if (is_string != 0) {
-                       _pam_log_debug(pamh, ctrl, LOG_DEBUG, "[pamh: 0x%08x] STATE: %s(%s) = \"%s\" (0x%08x)", (uint32) pamh, type, key, (const char *) data, (uint32) data);
+                       _pam_log_debug(pamh, ctrl, LOG_DEBUG, "[pamh: %p] STATE: %s(%s) = \"%s\" (%p)", pamh, type, key, (const char *) data, data);
                } else {
-                       _pam_log_debug(pamh, ctrl, LOG_DEBUG, "[pamh: 0x%08x] STATE: %s(%s) = 0x%08x", (uint32) pamh, type, key, (uint32) data);
+                       _pam_log_debug(pamh, ctrl, LOG_DEBUG, "[pamh: %p] STATE: %s(%s) = %p", pamh, type, key, data);
                }
        }
 }
@@ -193,8 +195,10 @@ static void _pam_log_state(const pam_handle_t *pamh, int ctrl)
 
        _PAM_LOG_STATE_DATA_STRING(pamh, ctrl, PAM_WINBIND_HOMEDIR);
        _PAM_LOG_STATE_DATA_STRING(pamh, ctrl, PAM_WINBIND_LOGONSCRIPT);
+       _PAM_LOG_STATE_DATA_STRING(pamh, ctrl, PAM_WINBIND_LOGONSERVER);
        _PAM_LOG_STATE_DATA_STRING(pamh, ctrl, PAM_WINBIND_PROFILEPATH);
        _PAM_LOG_STATE_DATA_STRING(pamh, ctrl, PAM_WINBIND_NEW_AUTHTOK_REQD); /* Use atoi to get PAM result code */
+       _PAM_LOG_STATE_DATA_STRING(pamh, ctrl, PAM_WINBIND_NEW_AUTHTOK_REQD_DURING_AUTH);
        _PAM_LOG_STATE_DATA_POINTER(pamh, ctrl, PAM_WINBIND_PWD_LAST_SET);
 }
 
@@ -227,23 +231,23 @@ static int _pam_parse(const pam_handle_t *pamh, int flags, int argc, const char
                goto config_from_pam;
        }
 
-       if (iniparser_getboolean(d, "global:debug", False)) {
+       if (iniparser_getboolean(d, "global:debug", false)) {
                ctrl |= WINBIND_DEBUG_ARG;
        }
 
-       if (iniparser_getboolean(d, "global:debug_state", False)) {
+       if (iniparser_getboolean(d, "global:debug_state", false)) {
                ctrl |= WINBIND_DEBUG_STATE;
        }
 
-       if (iniparser_getboolean(d, "global:cached_login", False)) {
+       if (iniparser_getboolean(d, "global:cached_login", false)) {
                ctrl |= WINBIND_CACHED_LOGIN;
        }
 
-       if (iniparser_getboolean(d, "global:krb5_auth", False)) {
+       if (iniparser_getboolean(d, "global:krb5_auth", false)) {
                ctrl |= WINBIND_KRB5_AUTH;
        }
 
-       if (iniparser_getboolean(d, "global:silent", False)) {
+       if (iniparser_getboolean(d, "global:silent", false)) {
                ctrl |= WINBIND_SILENT;
        }
 
@@ -256,10 +260,14 @@ static int _pam_parse(const pam_handle_t *pamh, int flags, int argc, const char
                ctrl |= WINBIND_REQUIRED_MEMBERSHIP;
        }
 
-       if (iniparser_getboolean(d, "global:try_first_pass", False)) {
+       if (iniparser_getboolean(d, "global:try_first_pass", false)) {
                ctrl |= WINBIND_TRY_FIRST_PASS_ARG;
        }
 
+       if (iniparser_getint(d, "global:warn_pwd_expire", 0)) {
+               ctrl |= WINBIND_WARN_PWD_EXPIRE;
+       }
+
 config_from_pam:
        /* step through arguments */
        for (i=argc,v=argv; i-- > 0; ++v) {
@@ -269,6 +277,8 @@ config_from_pam:
                        ctrl |= WINBIND_DEBUG_ARG;
                else if (!strcasecmp(*v, "debug_state"))
                        ctrl |= WINBIND_DEBUG_STATE;
+               else if (!strcasecmp(*v, "silent"))
+                       ctrl |= WINBIND_SILENT;
                else if (!strcasecmp(*v, "use_authtok"))
                        ctrl |= WINBIND_USE_AUTHTOK_ARG;
                else if (!strcasecmp(*v, "use_first_pass"))
@@ -309,7 +319,7 @@ static void _pam_winbind_cleanup_func(pam_handle_t *pamh, void *data, int error_
 {
        int ctrl = _pam_parse(pamh, 0, 0, NULL, NULL);
        if (_pam_log_is_debug_state_enabled(ctrl)) {
-               _pam_log_debug(pamh, ctrl, LOG_DEBUG, "[pamh: 0x%08x] CLEAN: cleaning up PAM data 0x%08x (error_status = %d)", (uint32) pamh, (uint32) data, error_status);
+               _pam_log_debug(pamh, ctrl, LOG_DEBUG, "[pamh: %p] CLEAN: cleaning up PAM data %p (error_status = %d)", pamh, data, error_status);
        }
        SAFE_FREE(data);
 }
@@ -372,15 +382,19 @@ static int converse(pam_handle_t *pamh, int nargs,
 }
 
 
-static int _make_remark(pam_handle_t * pamh, int type, const char *text)
+static int _make_remark(pam_handle_t * pamh, int flags, int type, const char *text)
 {
        int retval = PAM_SUCCESS;
 
        struct pam_message *pmsg[1], msg[1];
        struct pam_response *resp;
        
+       if (flags & WINBIND_SILENT) {
+               return PAM_SUCCESS;
+       }
+
        pmsg[0] = &msg[0];
-       msg[0].msg = CONST_DISCARD(char *, text);
+       msg[0].msg = discard_const_p(char, text);
        msg[0].msg_style = type;
        
        resp = NULL;
@@ -392,7 +406,7 @@ static int _make_remark(pam_handle_t * pamh, int type, const char *text)
        return retval;
 }
 
-static int _make_remark_v(pam_handle_t * pamh, int type, const char *format, va_list args)
+static int _make_remark_v(pam_handle_t * pamh, int flags, int type, const char *format, va_list args)
 {
        char *var;
        int ret;
@@ -403,18 +417,19 @@ static int _make_remark_v(pam_handle_t * pamh, int type, const char *format, va_
                return ret;
        }
 
-       ret = _make_remark(pamh, type, var);
+       ret = _make_remark(pamh, flags, type, var);
        SAFE_FREE(var);
        return ret;
 }
 
-static int _make_remark_format(pam_handle_t * pamh, int type, const char *format, ...)
+static int _make_remark_format(pam_handle_t * pamh, int flags, int type, const char *format, ...) PRINTF_ATTRIBUTE(4,5);
+static int _make_remark_format(pam_handle_t * pamh, int flags, int type, const char *format, ...)
 {
        int ret;
        va_list args;
 
        va_start(args, format);
-       ret = _make_remark_v(pamh, type, format, args);
+       ret = _make_remark_v(pamh, flags, type, format, args);
        va_end(args);
        return ret;
 }
@@ -425,23 +440,23 @@ static int pam_winbind_request(pam_handle_t * pamh, int ctrl,
                               struct winbindd_response *response)
 {
        /* Fill in request and send down pipe */
-       init_request(request, req_type);
+       winbindd_init_request(request, req_type);
        
-       if (write_sock(request, sizeof(*request), 0) == -1) {
+       if (winbind_write_sock(request, sizeof(*request), 0, 0) == -1) {
                _pam_log(pamh, ctrl, LOG_ERR, "pam_winbind_request: write to socket failed!");
-               close_sock();
+               winbind_close_sock();
                return PAM_SERVICE_ERR;
        }
        
        /* Wait for reply */
-       if (read_reply(response) == -1) {
+       if (winbindd_read_reply(response) == -1) {
                _pam_log(pamh, ctrl, LOG_ERR, "pam_winbind_request: read from socket failed!");
-               close_sock();
+               winbind_close_sock();
                return PAM_SERVICE_ERR;
        }
 
        /* We are done with the socket - close it and avoid mischeif */
-       close_sock();
+       winbind_close_sock();
 
        /* Copy reply data from socket */
        if (response->result == WINBINDD_OK) {
@@ -453,8 +468,12 @@ static int pam_winbind_request(pam_handle_t * pamh, int ctrl,
 
                case WINBINDD_GETPWNAM:
                case WINBINDD_LOOKUPNAME:
-                       _pam_log(pamh, ctrl, LOG_ERR, "request failed: %s, NT error was %s", 
+                       if (strlen(response->data.auth.nt_status_string) > 0) {
+                               _pam_log(pamh, ctrl, LOG_ERR, "request failed, NT error was %s", 
                                response->data.auth.nt_status_string);
+                       } else {
+                               _pam_log(pamh, ctrl, LOG_ERR, "request failed");
+                       }
                        return PAM_USER_UNKNOWN;
                default:
                        break;
@@ -510,15 +529,19 @@ static int pam_winbind_request_log(pam_handle_t * pamh,
                }        
                return retval;
        case PAM_SUCCESS:
-               if (req_type == WINBINDD_PAM_AUTH) {
-                       /* Otherwise, the authentication looked good */
-                       _pam_log(pamh, ctrl, LOG_NOTICE, "user '%s' granted access", user);
-               } else if (req_type == WINBINDD_PAM_CHAUTHTOK) {
-                       /* Otherwise, the authentication looked good */
-                       _pam_log(pamh, ctrl, LOG_NOTICE, "user '%s' password changed", user);
-               } else { 
-                       /* Otherwise, the authentication looked good */
-                       _pam_log(pamh, ctrl, LOG_NOTICE, "user '%s' OK", user);
+               /* Otherwise, the authentication looked good */
+               switch (req_type) {
+                       case WINBINDD_INFO:
+                               break;
+                       case WINBINDD_PAM_AUTH:
+                               _pam_log(pamh, ctrl, LOG_NOTICE, "user '%s' granted access", user);
+                               break;
+                       case WINBINDD_PAM_CHAUTHTOK:
+                               _pam_log(pamh, ctrl, LOG_NOTICE, "user '%s' password changed", user);
+                               break;
+                       default:
+                               _pam_log(pamh, ctrl, LOG_NOTICE, "user '%s' OK", user);
+                               break;
                }
        
                return retval;
@@ -530,43 +553,90 @@ static int pam_winbind_request_log(pam_handle_t * pamh,
        }
 }
 
-static BOOL _pam_send_password_expiry_message(pam_handle_t *pamh, time_t next_change, time_t now) 
+/**
+ * send a password expiry message if required
+ * 
+ * @param pamh PAM handle
+ * @param ctrl PAM winbind options.
+ * @param next_change expected (calculated) next expiry date.
+ * @param already_expired pointer to a boolean to indicate if the password is
+ *        already expired.
+ *
+ * @return boolean Returns true if message has been sent, false if not.
+ */
+
+static bool _pam_send_password_expiry_message(pam_handle_t *pamh,
+                                             int ctrl,
+                                             time_t next_change,
+                                             time_t now,
+                                             int warn_pwd_expire,
+                                             bool *already_expired)
 {
        int days = 0;
        struct tm tm_now, tm_next_change;
 
+       if (already_expired) {
+               *already_expired = false;
+       }
+
+       if (next_change <= now) {
+               PAM_WB_REMARK_DIRECT(pamh, ctrl, "NT_STATUS_PASSWORD_EXPIRED");
+               if (already_expired) {
+                       *already_expired = true;
+               }
+               return true;
+       }
+
        if ((next_change < 0) ||
-           (next_change < now) ||
-           (next_change > now + DAYS_TO_WARN_BEFORE_PWD_EXPIRES * SECONDS_PER_DAY)) {
-               return False;
+           (next_change > now + warn_pwd_expire * SECONDS_PER_DAY)) {
+               return false;
        }
 
        if ((localtime_r(&now, &tm_now) == NULL) || 
            (localtime_r(&next_change, &tm_next_change) == NULL)) {
-               return False;
+               return false;
        }
 
        days = (tm_next_change.tm_yday+tm_next_change.tm_year*365) - (tm_now.tm_yday+tm_now.tm_year*365);
 
        if (days == 0) {
-               _make_remark(pamh, PAM_TEXT_INFO, "Your password expires today");
-               return True;
+               _make_remark(pamh, ctrl, PAM_TEXT_INFO, "Your password expires today");
+               return true;
        } 
        
-       if (days > 0 && days < DAYS_TO_WARN_BEFORE_PWD_EXPIRES) {
-               _make_remark_format(pamh, PAM_TEXT_INFO, "Your password will expire in %d %s", 
+       if (days > 0 && days < warn_pwd_expire) {
+               _make_remark_format(pamh, ctrl, PAM_TEXT_INFO, "Your password will expire in %d %s", 
                        days, (days > 1) ? "days":"day");
-               return True;
+               return true;
        }
 
-       return False;
+       return false;
 }
 
-static void _pam_warn_password_expires_in_future(pam_handle_t *pamh, struct winbindd_response *response)
+/**
+ * Send a warning if the password expires in the near future
+ *
+ * @param pamh PAM handle
+ * @param ctrl PAM winbind options.
+ * @param response The full authentication response structure.
+ * @param already_expired boolean, is the pwd already expired?
+ *
+ * @return void.
+ */
+
+static void _pam_warn_password_expiry(pam_handle_t *pamh, 
+                                     int flags, 
+                                     const struct winbindd_response *response,
+                                     int warn_pwd_expire,
+                                     bool *already_expired)
 {
        time_t now = time(NULL);
        time_t next_change = 0;
 
+       if (already_expired) {
+               *already_expired = false;
+       }
+
        /* accounts with ACB_PWNOEXP set never receive a warning */
        if (response->data.auth.info3.acct_flags & ACB_PWNOEXP) {
                return;
@@ -580,11 +650,15 @@ static void _pam_warn_password_expires_in_future(pam_handle_t *pamh, struct winb
        /* check if the info3 must change timestamp has been set */
        next_change = response->data.auth.info3.pass_must_change_time;
 
-       if (_pam_send_password_expiry_message(pamh, next_change, now)) {
+       if (_pam_send_password_expiry_message(pamh, flags, next_change, now,
+                                             warn_pwd_expire,
+                                             already_expired)) {
                return;
        }
 
        /* now check for the global password policy */
+       /* good catch from Ralf Haferkamp: an expiry of "never" is translated
+        * to -1 */
        if (response->data.auth.policy.expire <= 0) {
                return;
        }
@@ -592,7 +666,9 @@ static void _pam_warn_password_expires_in_future(pam_handle_t *pamh, struct winb
        next_change = response->data.auth.info3.pass_last_set_time + 
                      response->data.auth.policy.expire;
 
-       if (_pam_send_password_expiry_message(pamh, next_change, now)) {
+       if (_pam_send_password_expiry_message(pamh, flags, next_change, now,
+                                             warn_pwd_expire,
+                                             already_expired)) {
                return;
        }
 
@@ -601,7 +677,7 @@ static void _pam_warn_password_expires_in_future(pam_handle_t *pamh, struct winb
 
 #define IS_SID_STRING(name) (strncmp("S-", name, 2) == 0)
 
-static BOOL safe_append_string(char *dest,
+static bool safe_append_string(char *dest,
                        const char *src,
                        int dest_buffer_size)
 /**
@@ -612,21 +688,21 @@ static BOOL safe_append_string(char *dest,
  * @param src Source string buffer.
  * @param dest_buffer_size Size of dest buffer in bytes.
  *
- * @return False if dest buffer is not big enough (no bytes copied), True on success.
+ * @return false if dest buffer is not big enough (no bytes copied), true on success.
  */
 {
        int dest_length = strlen(dest);
        int src_length = strlen(src);
 
        if ( dest_length + src_length + 1 > dest_buffer_size ) {
-               return False;
+               return false;
        }
 
        memcpy(dest + dest_length, src, src_length + 1);
-       return True;
+       return true;
 }
 
-static BOOL winbind_name_to_sid_string(pam_handle_t *pamh,
+static bool winbind_name_to_sid_string(pam_handle_t *pamh,
                                int ctrl,
                                const char *user,
                                const char *name,
@@ -642,7 +718,7 @@ static BOOL winbind_name_to_sid_string(pam_handle_t *pamh,
  * @param sid_list_buffer Where to append the string sid.
  * @param sid_list_buffer Size of sid_list_buffer (in bytes).
  *
- * @return False on failure, True on success.
+ * @return false on failure, true on success.
  */
 {
        const char* sid_string;
@@ -665,20 +741,20 @@ static BOOL winbind_name_to_sid_string(pam_handle_t *pamh,
 
                if (pam_winbind_request_log(pamh, ctrl, WINBINDD_LOOKUPNAME, &sid_request, &sid_response, user)) {
                        _pam_log(pamh, ctrl, LOG_INFO, "could not lookup name: %s\n", name); 
-                       return False;
+                       return false;
                }
 
                sid_string = sid_response.data.sid.sid;
        }
 
        if (!safe_append_string(sid_list_buffer, sid_string, sid_list_buffer_size)) {
-               return False;
+               return false;
        }
 
-       return True;
+       return true;
 }
 
-static BOOL winbind_name_list_to_sid_string_list(pam_handle_t *pamh,
+static bool winbind_name_list_to_sid_string_list(pam_handle_t *pamh,
                                int ctrl,
                                const char *user,
                                const char *name_list,
@@ -694,10 +770,10 @@ static BOOL winbind_name_list_to_sid_string_list(pam_handle_t *pamh,
  * @param sid_list_buffer Where to put the list of string sids.
  * @param sid_list_buffer Size of sid_list_buffer (in bytes).
  *
- * @return False on failure, True on success.
+ * @return false on failure, true on success.
  */
 {
-       BOOL result = False;
+       bool result = false;
        char *current_name = NULL;
        const char *search_location;
        const char *comma;
@@ -730,13 +806,165 @@ static BOOL winbind_name_list_to_sid_string_list(pam_handle_t *pamh,
                goto out;
        }
 
-       result = True;
+       result = true;
 
 out:
        SAFE_FREE(current_name);
        return result;
 }
 
+/**
+ * put krb5ccname variable into environment
+ *
+ * @param pamh PAM handle
+ * @param ctrl PAM winbind options.
+ * @param krb5ccname env variable retrieved from winbindd.
+ *
+ * @return void.
+ */
+
+static void _pam_setup_krb5_env(pam_handle_t *pamh, int ctrl, const char *krb5ccname)
+{
+       char var[PATH_MAX];
+       int ret;
+
+       if (off(ctrl, WINBIND_KRB5_AUTH)) {
+               return;
+       }
+
+       if (!krb5ccname || (strlen(krb5ccname) == 0)) {
+               return;
+       }
+
+       _pam_log_debug(pamh, ctrl, LOG_DEBUG, "request returned KRB5CCNAME: %s", krb5ccname);
+       
+       if (snprintf(var, sizeof(var), "KRB5CCNAME=%s", krb5ccname) == -1) {
+               return;
+       }
+       
+       ret = pam_putenv(pamh, var);
+       if (ret) {
+               _pam_log(pamh, ctrl, LOG_ERR, "failed to set KRB5CCNAME to %s: %s", 
+                       var, pam_strerror(pamh, ret));
+       }
+}      
+
+/**
+ * Set string into the PAM stack.
+ *
+ * @param pamh PAM handle
+ * @param ctrl PAM winbind options.
+ * @param data_name Key name for pam_set_data.
+ * @param value String value.
+ *
+ * @return void.
+ */
+
+static void _pam_set_data_string(pam_handle_t *pamh, int ctrl, const char *data_name, const char *value)
+{
+       int ret;
+
+       if ( !data_name || !value || (strlen(data_name) == 0) || (strlen(value) == 0) ) {
+               return;
+       }
+
+       ret = pam_set_data(pamh, data_name, (void *)strdup(value), _pam_winbind_cleanup_func);
+       if (ret) {
+               _pam_log_debug(pamh, ctrl, LOG_DEBUG, "Could not set data %s: %s\n", 
+                       data_name, pam_strerror(pamh, ret));
+       }
+
+}
+
+/**
+ * Set info3 strings into the PAM stack.
+ *
+ * @param pamh PAM handle
+ * @param ctrl PAM winbind options.
+ * @param data_name Key name for pam_set_data.
+ * @param value String value.
+ *
+ * @return void.
+ */
+
+static void _pam_set_data_info3(pam_handle_t *pamh, int ctrl, struct winbindd_response *response)
+{
+       _pam_set_data_string(pamh, ctrl, PAM_WINBIND_HOMEDIR, response->data.auth.info3.home_dir);
+       _pam_set_data_string(pamh, ctrl, PAM_WINBIND_LOGONSCRIPT, response->data.auth.info3.logon_script);
+       _pam_set_data_string(pamh, ctrl, PAM_WINBIND_LOGONSERVER, response->data.auth.info3.logon_srv);
+       _pam_set_data_string(pamh, ctrl, PAM_WINBIND_PROFILEPATH, response->data.auth.info3.profile_path);
+}
+
+/**
+ * Free info3 strings in the PAM stack.
+ *
+ * @param pamh PAM handle
+ *
+ * @return void.
+ */
+
+static void _pam_free_data_info3(pam_handle_t *pamh)
+{
+       pam_set_data(pamh, PAM_WINBIND_HOMEDIR, NULL, NULL);
+       pam_set_data(pamh, PAM_WINBIND_LOGONSCRIPT, NULL, NULL);
+       pam_set_data(pamh, PAM_WINBIND_LOGONSERVER, NULL, NULL);
+       pam_set_data(pamh, PAM_WINBIND_PROFILEPATH, NULL, NULL);
+}
+
+/**
+ * Send PAM_ERROR_MSG for cached or grace logons.
+ *
+ * @param pamh PAM handle
+ * @param ctrl PAM winbind options.
+ * @param username User in PAM request.
+ * @param info3_user_flgs Info3 flags containing logon type bits.
+ *
+ * @return void.
+ */
+
+static void _pam_warn_logon_type(pam_handle_t *pamh, int ctrl, const char *username, uint32_t info3_user_flgs)
+{
+       /* inform about logon type */
+       if (PAM_WB_GRACE_LOGON(info3_user_flgs)) {
+
+               _make_remark(pamh, ctrl, PAM_ERROR_MSG, 
+                       "Grace login. Please change your password as soon you're online again");
+               _pam_log_debug(pamh, ctrl, LOG_DEBUG,
+                       "User %s logged on using grace logon\n", username);
+
+       } else if (PAM_WB_CACHED_LOGON(info3_user_flgs)) {
+
+               _make_remark(pamh, ctrl, PAM_ERROR_MSG, 
+                       "Domain Controller unreachable, using cached credentials instead. Network resources may be unavailable");
+               _pam_log_debug(pamh, ctrl, LOG_DEBUG,
+                       "User %s logged on using cached credentials\n", username);
+       }
+}
+
+/**
+ * Send PAM_ERROR_MSG for krb5 errors.
+ *
+ * @param pamh PAM handle
+ * @param ctrl PAM winbind options.
+ * @param username User in PAM request.
+ * @param info3_user_flgs Info3 flags containing logon type bits.
+ *
+ * @return void.
+ */
+
+static void _pam_warn_krb5_failure(pam_handle_t *pamh, int ctrl, const char *username, uint32_t info3_user_flgs)
+{
+       if (PAM_WB_KRB5_CLOCK_SKEW(info3_user_flgs)) {
+               _make_remark(pamh, ctrl, PAM_ERROR_MSG, 
+                            "Failed to establish your Kerberos Ticket cache "
+                            "due time differences\n" 
+                            "with the domain controller.  "
+                            "Please verify the system time.\n");               
+               _pam_log_debug(pamh, ctrl, LOG_DEBUG,
+                       "User %s: Clock skew when getting Krb5 TGT\n", username);
+       }
+}
+
 /**
  * Compose Password Restriction String for a PAM_ERROR_MSG conversation.
  *
@@ -813,6 +1041,7 @@ static int winbind_auth_request(pam_handle_t * pamh,
                                const char *pass, 
                                const char *member, 
                                const char *cctype,
+                               const int warn_pwd_expire,
                                struct winbindd_response *p_response,
                                time_t *pwd_last_set,
                                char **user_ret)
@@ -820,6 +1049,7 @@ static int winbind_auth_request(pam_handle_t * pamh,
        struct winbindd_request request;
        struct winbindd_response response;
        int ret;
+       bool already_expired = false;
 
        ZERO_STRUCT(request);
        ZERO_STRUCT(response);
@@ -839,14 +1069,9 @@ static int winbind_auth_request(pam_handle_t * pamh,
        
        request.flags = WBFLAG_PAM_INFO3_TEXT | WBFLAG_PAM_CONTACT_TRUSTDOM;
 
-       if (ctrl & WINBIND_KRB5_AUTH) {
-
+       if (ctrl & (WINBIND_KRB5_AUTH|WINBIND_CACHED_LOGIN)) {
                struct passwd *pwd = NULL;
 
-               _pam_log_debug(pamh, ctrl, LOG_DEBUG, "enabling krb5 login flag\n"); 
-
-               request.flags |= WBFLAG_PAM_KRB5 | WBFLAG_PAM_FALLBACK_AFTER_KRB5;
-
                pwd = getpwnam(user);
                if (pwd == NULL) {
                        return PAM_USER_UNKNOWN;
@@ -854,6 +1079,13 @@ static int winbind_auth_request(pam_handle_t * pamh,
                request.data.auth.uid = pwd->pw_uid;
        }
 
+       if (ctrl & WINBIND_KRB5_AUTH) {
+
+               _pam_log_debug(pamh, ctrl, LOG_DEBUG, "enabling krb5 login flag\n"); 
+
+               request.flags |= WBFLAG_PAM_KRB5 | WBFLAG_PAM_FALLBACK_AFTER_KRB5;
+       }
+
        if (ctrl & WINBIND_CACHED_LOGIN) {
                _pam_log_debug(pamh, ctrl, LOG_DEBUG, "enabling cached login flag\n"); 
                request.flags |= WBFLAG_PAM_CACHED_LOGIN;
@@ -889,23 +1121,6 @@ static int winbind_auth_request(pam_handle_t * pamh,
                *pwd_last_set = response.data.auth.info3.pass_last_set_time;
        }
 
-       if ((ctrl & WINBIND_KRB5_AUTH) && 
-           response.data.auth.krb5ccname[0] != '\0') {
-
-               char var[PATH_MAX];
-
-               _pam_log_debug(pamh, ctrl, LOG_DEBUG, "request returned KRB5CCNAME: %s", 
-                              response.data.auth.krb5ccname);
-       
-               snprintf(var, sizeof(var), "KRB5CCNAME=%s", response.data.auth.krb5ccname);
-       
-               ret = pam_putenv(pamh, var);
-               if (ret != PAM_SUCCESS) {
-                       _pam_log(pamh, ctrl, LOG_ERR, "failed to set KRB5CCNAME to %s", var);
-                       return ret;
-               }
-       }
-
        if (p_response) {
                /* We want to process the response in the caller. */
                *p_response = response;
@@ -913,101 +1128,60 @@ static int winbind_auth_request(pam_handle_t * pamh,
        }
 
        if (ret) {
-               PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_PASSWORD_EXPIRED");
-               PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_PASSWORD_MUST_CHANGE");
-               PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_INVALID_WORKSTATION");
-               PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_INVALID_LOGON_HOURS");
-               PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_ACCOUNT_EXPIRED");
-               PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_ACCOUNT_DISABLED");
-               PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_ACCOUNT_LOCKED_OUT");
-               PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT");
-               PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_NOLOGON_SERVER_TRUST_ACCOUNT");
-               PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT");
-               PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND");
-               PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_NO_LOGON_SERVERS");
-       }
-
-       /* handle the case where the auth was ok, but the password must expire right now */
-       /* good catch from Ralf Haferkamp: an expiry of "never" is translated to -1 */
-       if ( ! (response.data.auth.info3.acct_flags & ACB_PWNOEXP) &&
-            ! (PAM_WB_GRACE_LOGON(response.data.auth.info3.user_flgs)) &&
-           (response.data.auth.policy.expire > 0) && 
-           (response.data.auth.info3.pass_last_set_time + response.data.auth.policy.expire < time(NULL))) {
-
-               ret = PAM_AUTHTOK_EXPIRED;
-
-               _pam_log_debug(pamh, ctrl, LOG_DEBUG,"Password has expired (Password was last set: %d, "
-                              "the policy says it should expire here %d (now it's: %d)\n",
-                              response.data.auth.info3.pass_last_set_time,
-                              response.data.auth.info3.pass_last_set_time + response.data.auth.policy.expire,
-                              time(NULL));
-
-               PAM_WB_REMARK_DIRECT_RET(pamh, "NT_STATUS_PASSWORD_EXPIRED");
-
-       }
-
-       /* warn a user if the password is about to expire soon */
-       _pam_warn_password_expires_in_future(pamh, &response);
-
-       /* inform about logon type */
-       if (PAM_WB_GRACE_LOGON(response.data.auth.info3.user_flgs)) {
-
-               _make_remark(pamh, PAM_ERROR_MSG, 
-                       "Grace login. Please change your password as soon you're online again");
-               _pam_log_debug(pamh, ctrl, LOG_DEBUG,
-                       "User %s logged on using grace logon\n", user);
-
-       } else if (PAM_WB_CACHED_LOGON(response.data.auth.info3.user_flgs)) {
-
-               _make_remark(pamh, PAM_ERROR_MSG, 
-                       "Logging on using cached account. Network resources can be unavailable");
-               _pam_log_debug(pamh, ctrl, LOG_DEBUG,
-                       "User %s logged on using cached account\n", user);
+               PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_PASSWORD_EXPIRED");
+               PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_PASSWORD_MUST_CHANGE");
+               PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_INVALID_WORKSTATION");
+               PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_INVALID_LOGON_HOURS");
+               PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_ACCOUNT_EXPIRED");
+               PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_ACCOUNT_DISABLED");
+               PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_ACCOUNT_LOCKED_OUT");
+               PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT");
+               PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_NOLOGON_SERVER_TRUST_ACCOUNT");
+               PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT");
+               PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND");
+               PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_NO_LOGON_SERVERS");
+               PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_WRONG_PASSWORD");
+               PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_ACCESS_DENIED");
        }
 
-       /* save the CIFS homedir for pam_cifs / pam_mount */
-       if (response.data.auth.info3.home_dir[0] != '\0') {
+       if (ret == PAM_SUCCESS) {
 
-               int ret2 = pam_set_data(pamh, PAM_WINBIND_HOMEDIR,
-                                       (void *) strdup(response.data.auth.info3.home_dir),
-                                       _pam_winbind_cleanup_func);
-               if (ret2) {
-                       _pam_log_debug(pamh, ctrl, LOG_DEBUG, "Could not set data: %s", 
-                                      pam_strerror(pamh, ret2));
+               /* warn a user if the password is about to expire soon */
+               _pam_warn_password_expiry(pamh, ctrl, &response,
+                                         warn_pwd_expire,
+                                         &already_expired);
+
+               if (already_expired == true) {
+                       _pam_log_debug(pamh, ctrl, LOG_DEBUG, "Password has expired "
+                                      "(Password was last set: %lld, the policy says "
+                                      "it should expire here %lld (now it's: %lu))\n",
+                                      response.data.auth.info3.pass_last_set_time, 
+                                      response.data.auth.info3.pass_last_set_time +
+                                      response.data.auth.policy.expire,
+                                      time(NULL));
+
+                       return PAM_AUTHTOK_EXPIRED;
                }
 
-       }
+               /* inform about logon type */
+               _pam_warn_logon_type(pamh, ctrl, user, response.data.auth.info3.user_flgs);
 
-       /* save the logon script path for other PAM modules */
-       if (response.data.auth.info3.logon_script[0] != '\0') {
+               /* inform about krb5 failures */
+               _pam_warn_krb5_failure(pamh, ctrl, user, response.data.auth.info3.user_flgs);
 
-               int ret2 = pam_set_data(pamh, PAM_WINBIND_LOGONSCRIPT, 
-                                       (void *) strdup(response.data.auth.info3.logon_script), 
-                                       _pam_winbind_cleanup_func);
-               if (ret2) {
-                       _pam_log_debug(pamh, ctrl, LOG_DEBUG, "Could not set data: %s", 
-                                      pam_strerror(pamh, ret2));
-               }
-       }
+               /* set some info3 info for other modules in the stack */
+               _pam_set_data_info3(pamh, ctrl, &response);
 
-       /* save the profile path for other PAM modules */
-       if (response.data.auth.info3.profile_path[0] != '\0') {
+               /* put krb5ccname into env */
+               _pam_setup_krb5_env(pamh, ctrl, response.data.auth.krb5ccname);
 
-               int ret2 = pam_set_data(pamh, PAM_WINBIND_PROFILEPATH, 
-                                       (void *) strdup(response.data.auth.info3.profile_path), 
-                                       _pam_winbind_cleanup_func);
-               if (ret2) {
-                       _pam_log_debug(pamh, ctrl, LOG_DEBUG, "Could not set data: %s", 
-                                      pam_strerror(pamh, ret2));
+               /* If winbindd returned a username, return the pointer to it here. */
+               if (user_ret && response.extra_data.data) {
+                       /* We have to trust it's a null terminated string. */
+                       *user_ret = (char *)response.extra_data.data;
                }
        }
 
-       /* If winbindd returned a username, return the pointer to it here. */
-       if (user_ret && response.extra_data.data) {
-               /* We have to trust it's a null terminated string. */
-               *user_ret = (char *)response.extra_data.data;
-       }
-
        return ret;
 }
 
@@ -1055,19 +1229,19 @@ static int winbind_chauthtok_request(pam_handle_t * pamh,
                return ret;
        }
 
-       PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_BACKUP_CONTROLLER");
-       PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND");
-       PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_NO_LOGON_SERVERS");
-       PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_ACCESS_DENIED");
+       PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_BACKUP_CONTROLLER");
+       PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND");
+       PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_NO_LOGON_SERVERS");
+       PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_ACCESS_DENIED");
 
        /* TODO: tell the min pwd length ? */
-       PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_PWD_TOO_SHORT");
+       PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_PWD_TOO_SHORT");
 
        /* TODO: tell the minage ? */
-       PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_PWD_TOO_RECENT");
+       PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_PWD_TOO_RECENT");
 
        /* TODO: tell the history length ? */
-       PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_PWD_HISTORY_CONFLICT");
+       PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_PWD_HISTORY_CONFLICT");
 
        if (!strcasecmp(response.data.auth.nt_status_string, "NT_STATUS_PASSWORD_RESTRICTION")) {
 
@@ -1080,17 +1254,17 @@ static int winbind_chauthtok_request(pam_handle_t * pamh,
                        case REJECT_REASON_OTHER:
                                if ((response.data.auth.policy.min_passwordage > 0) &&
                                    (pwd_last_set + response.data.auth.policy.min_passwordage > time(NULL))) {
-                                       PAM_WB_REMARK_DIRECT(pamh, "NT_STATUS_PWD_TOO_RECENT");
+                                       PAM_WB_REMARK_DIRECT(pamh, ctrl, "NT_STATUS_PWD_TOO_RECENT");
                                }
                                break;
                        case REJECT_REASON_TOO_SHORT:
-                               PAM_WB_REMARK_DIRECT(pamh, "NT_STATUS_PWD_TOO_SHORT");
+                               PAM_WB_REMARK_DIRECT(pamh, ctrl, "NT_STATUS_PWD_TOO_SHORT");
                                break;
                        case REJECT_REASON_IN_HISTORY:
-                               PAM_WB_REMARK_DIRECT(pamh, "NT_STATUS_PWD_HISTORY_CONFLICT");
+                               PAM_WB_REMARK_DIRECT(pamh, ctrl, "NT_STATUS_PWD_HISTORY_CONFLICT");
                                break;
                        case REJECT_REASON_NOT_COMPLEX:
-                               _make_remark(pamh, PAM_ERROR_MSG, "Password does not meet complexity requirements");
+                               _make_remark(pamh, ctrl, PAM_ERROR_MSG, "Password does not meet complexity requirements");
                                break;
                        default:
                                _pam_log_debug(pamh, ctrl, LOG_DEBUG,
@@ -1101,7 +1275,7 @@ static int winbind_chauthtok_request(pam_handle_t * pamh,
 
                pwd_restriction_string = _pam_compose_pwd_restriction_string(&response);
                if (pwd_restriction_string) {
-                       _make_remark(pamh, PAM_ERROR_MSG, pwd_restriction_string);
+                       _make_remark(pamh, ctrl, PAM_ERROR_MSG, pwd_restriction_string);
                        SAFE_FREE(pwd_restriction_string);
                }
        }
@@ -1226,10 +1400,10 @@ static int _winbind_read_password(pam_handle_t * pamh,
 
                /* prepare to converse */
 
-               if (comment != NULL) {
+               if (comment != NULL && off(ctrl, WINBIND_SILENT)) {
                        pmsg[0] = &msg[0];
                        msg[0].msg_style = PAM_TEXT_INFO;
-                       msg[0].msg = CONST_DISCARD(char *, comment);
+                       msg[0].msg = discard_const_p(char, comment);
                        i = 1;
                } else {
                        i = 0;
@@ -1237,13 +1411,13 @@ static int _winbind_read_password(pam_handle_t * pamh,
 
                pmsg[i] = &msg[i];
                msg[i].msg_style = PAM_PROMPT_ECHO_OFF;
-               msg[i++].msg = CONST_DISCARD(char *, prompt1);
+               msg[i++].msg = discard_const_p(char, prompt1);
                replies = 1;
 
                if (prompt2 != NULL) {
                        pmsg[i] = &msg[i];
                        msg[i].msg_style = PAM_PROMPT_ECHO_OFF;
-                       msg[i++].msg = CONST_DISCARD(char *, prompt2);
+                       msg[i++].msg = discard_const_p(char, prompt2);
                        ++replies;
                }
                /* so call the conversation expecting i responses */
@@ -1264,7 +1438,7 @@ static int _winbind_read_password(pam_handle_t * pamh,
                                                    || strcmp(token, resp[i - 1].resp)) {
                                                        _pam_delete(token);     /* mistyped */
                                                        retval = PAM_AUTHTOK_RECOVER_ERR;
-                                                       _make_remark(pamh, PAM_ERROR_MSG, MISTYPED_PASS);
+                                                       _make_remark(pamh, ctrl, PAM_ERROR_MSG, MISTYPED_PASS);
                                                }
                                        }
                                } else {
@@ -1321,15 +1495,28 @@ const char *get_conf_item_string(const pam_handle_t *pamh,
 {
        int i = 0;
        const char *parm_opt = NULL;
-       char *key = NULL;
 
        if (!(ctrl & config_flag)) {
                goto out;
        }
 
        /* let the pam opt take precedence over the pam_winbind.conf option */
+       for ( i=0; i<argc; i++ ) {
+
+               if ((strncmp(argv[i], item, strlen(item)) == 0)) {
+                       char *p;
+
+                       if ( (p = strchr( argv[i], '=' )) == NULL) {
+                               _pam_log(pamh, ctrl, LOG_INFO, "no \"=\" delimiter for \"%s\" found\n", item);
+                               goto out;
+                       }
+                       _pam_log_debug(pamh, ctrl, LOG_INFO, "PAM config: %s '%s'\n", item, p+1);
+                       return p + 1;
+               }
+       }
 
        if (d != NULL) {
+               char *key = NULL;
 
                if (!asprintf(&key, "global:%s", item)) {
                        goto out;
@@ -1337,24 +1524,60 @@ const char *get_conf_item_string(const pam_handle_t *pamh,
 
                parm_opt = iniparser_getstr(d, key);
                SAFE_FREE(key);
+
+               _pam_log_debug(pamh, ctrl, LOG_INFO, "CONFIG file: %s '%s'\n", item, parm_opt);
        }
+out:
+       return parm_opt;
+}
 
-       for ( i=0; i<argc; i++ ) {
+int get_config_item_int(const pam_handle_t *pamh,
+                             int argc,
+                             const char **argv,
+                             int ctrl,
+                             dictionary *d,
+                             const char *item,
+                             int config_flag)
+{
+       int i, parm_opt = -1;
+
+       if (!(ctrl & config_flag)) {
+               goto out;
+       }
+
+       /* let the pam opt take precedence over the pam_winbind.conf option */
+       for (i = 0; i < argc; i++) {
 
                if ((strncmp(argv[i], item, strlen(item)) == 0)) {
                        char *p;
 
                        if ( (p = strchr( argv[i], '=' )) == NULL) {
-                               _pam_log(pamh, ctrl, LOG_INFO, "no \"=\" delimiter for \"%s\" found\n", item);
+                               _pam_log(pamh, ctrl, LOG_INFO,
+                                        "no \"=\" delimiter for \"%s\" found\n",
+                                        item);
                                goto out;
                        }
-                       _pam_log_debug(pamh, ctrl, LOG_INFO, "PAM config: %s '%s'\n", item, p+1);
-                       return p + 1;
+                       parm_opt = atoi(p + 1);
+                       _pam_log_debug(pamh, ctrl, LOG_INFO,
+                                      "PAM config: %s '%d'\n",
+                                      item, parm_opt);
+                       return parm_opt;
                }
        }
 
        if (d != NULL) {
-               _pam_log_debug(pamh, ctrl, LOG_INFO, "CONFIG file: %s '%s'\n", item, parm_opt);
+               char *key = NULL;
+
+               if (!asprintf(&key, "global:%s", item)) {
+                       goto out;
+               }
+
+               parm_opt = iniparser_getint(d, key, -1);
+               SAFE_FREE(key);
+
+               _pam_log_debug(pamh, ctrl, LOG_INFO,
+                              "CONFIG file: %s '%d'\n",
+                              item, parm_opt);
        }
 out:
        return parm_opt;
@@ -1375,6 +1598,105 @@ const char *get_member_from_config(const pam_handle_t *pamh, int argc, const cha
        return get_conf_item_string(pamh, argc, argv, ctrl, d, "require-membership-of", WINBIND_REQUIRED_MEMBERSHIP);
 }
 
+int get_warn_pwd_expire_from_config(const pam_handle_t *pamh,
+                                                         int argc,
+                                                         const char **argv,
+                                                         int ctrl,
+                                                         dictionary *d)
+{
+       int ret;
+       ret = get_config_item_int(pamh, argc, argv, ctrl, d,
+                                 "warn_pwd_expire", WINBIND_WARN_PWD_EXPIRE);
+       /* no or broken setting */
+       if (ret <= 0) {
+               return DEFAULT_DAYS_TO_WARN_BEFORE_PWD_EXPIRES;
+       }
+       return ret;
+}
+
+/**
+ * Retrieve the winbind separator.
+ *
+ * @param pamh PAM handle
+ * @param ctrl PAM winbind options.
+ *
+ * @return string separator character. NULL on failure.
+ */
+
+static char winbind_get_separator(pam_handle_t *pamh, int ctrl)
+{
+       struct winbindd_request request;
+       struct winbindd_response response;
+
+       ZERO_STRUCT(request);
+       ZERO_STRUCT(response);
+
+       if (pam_winbind_request_log(pamh, ctrl, WINBINDD_INFO, &request, &response, NULL)) {
+               return '\0';
+       }
+
+       return response.data.info.winbind_separator;
+}
+
+/**
+ * Convert a upn to a name.
+ *
+ * @param pamh PAM handle
+ * @param ctrl PAM winbind options.
+ * @param upn  USer UPN to be trabslated.
+ *
+ * @return converted name. NULL pointer on failure. Caller needs to free.
+ */
+
+static char* winbind_upn_to_username(pam_handle_t *pamh, int ctrl, const char *upn)
+{
+       struct winbindd_request req;
+       struct winbindd_response resp;
+       int retval;     
+       char *account_name;     
+       int account_name_len;
+       char sep;       
+
+       /* This cannot work when the winbind separator = @ */
+
+       sep = winbind_get_separator(pamh, ctrl);
+       if (!sep || sep == '@') {
+               return NULL;
+       }
+       
+       /* Convert the UPN to a SID */
+
+       ZERO_STRUCT(req);
+       ZERO_STRUCT(resp);
+
+       strncpy(req.data.name.dom_name, "",
+               sizeof(req.data.name.dom_name) - 1);
+       strncpy(req.data.name.name, upn,
+               sizeof(req.data.name.name) - 1);
+       retval = pam_winbind_request_log(pamh, ctrl, WINBINDD_LOOKUPNAME, 
+                                        &req, &resp, upn);
+       if ( retval != PAM_SUCCESS ) {          
+               return NULL;
+       }
+       
+       /* Convert the the SID back to the sAMAccountName */
+       
+       ZERO_STRUCT(req);
+       strncpy(req.data.sid, resp.data.sid.sid, sizeof(req.data.sid)-1);
+       ZERO_STRUCT(resp);
+       retval =  pam_winbind_request_log(pamh, ctrl, WINBINDD_LOOKUPSID, 
+                                         &req, &resp, upn);
+       if ( retval != PAM_SUCCESS ) {          
+               return NULL;
+       }
+       
+       account_name_len = asprintf(&account_name, "%s\\%s", 
+                                   resp.data.name.dom_name,
+                                   resp.data.name.name);
+
+       return account_name;
+}
+
 PAM_EXTERN
 int pam_sm_authenticate(pam_handle_t *pamh, int flags,
                        int argc, const char **argv)
@@ -1383,10 +1705,12 @@ int pam_sm_authenticate(pam_handle_t *pamh, int flags,
        const char *password;
        const char *member = NULL;
        const char *cctype = NULL;
+       int warn_pwd_expire;
        int retval = PAM_AUTH_ERR;
        dictionary *d = NULL;
        char *username_ret = NULL;
        char *new_authtok_required = NULL;
+       char *real_username = NULL;
 
        /* parse arguments */
        int ctrl = _pam_parse(pamh, flags, argc, argv, &d);
@@ -1405,6 +1729,44 @@ int pam_sm_authenticate(pam_handle_t *pamh, int flags,
                goto out;
        }
 
+
+#if defined(AIX)
+       /* Decode the user name since AIX does not support logn user
+          names by default.  The name is encoded as _#uid.  */
+
+       if ( username[0] == '_' ) {
+               uid_t id = atoi( &username[1] );
+               struct passwd *pw = NULL;               
+
+               if ( (id!=0) && ((pw = getpwuid( id )) != NULL) ) {
+                       real_username = strdup( pw->pw_name );
+               }
+       }
+#endif
+
+       if ( !real_username ) {
+               /* Just making a copy of the username we got from PAM */
+               if ( (real_username = strdup( username )) == NULL ) {
+                       _pam_log_debug(pamh, ctrl, LOG_DEBUG, 
+                                      "memory allocation failure when copying username");
+                       retval = PAM_SERVICE_ERR;
+                       goto out;
+               }
+       }       
+
+       /* Maybe this was a UPN */
+
+       if (strchr(real_username, '@') != NULL) {
+               char *samaccountname = NULL;
+               
+               samaccountname = winbind_upn_to_username(pamh, ctrl, 
+                                                        real_username);
+               if (samaccountname) {
+                       free(real_username);
+                       real_username = samaccountname;
+               }
+       }
+
        retval = _winbind_read_password(pamh, ctrl, NULL, 
                                        "Password: ", NULL,
                                        &password);
@@ -1419,22 +1781,28 @@ int pam_sm_authenticate(pam_handle_t *pamh, int flags,
 
 #ifdef DEBUG_PASSWORD
        _pam_log_debug(pamh, ctrl, LOG_INFO, "Verify user '%s' with password '%s'", 
-                      username, password);
+                      real_username, password);
 #else
-       _pam_log_debug(pamh, ctrl, LOG_INFO, "Verify user '%s'", username);
+       _pam_log_debug(pamh, ctrl, LOG_INFO, "Verify user '%s'", real_username);
 #endif
 
        member = get_member_from_config(pamh, argc, argv, ctrl, d);
 
        cctype = get_krb5_cc_type_from_config(pamh, argc, argv, ctrl, d);
 
+       warn_pwd_expire = get_warn_pwd_expire_from_config(pamh, argc, argv,
+                                                         ctrl, d);
+
        /* Now use the username to look up password */
-       retval = winbind_auth_request(pamh, ctrl, username, password, member,
-                                     cctype, NULL, NULL, &username_ret);
+       retval = winbind_auth_request(pamh, ctrl, real_username, password, member,
+                                     cctype, warn_pwd_expire, NULL, NULL, 
+                                     &username_ret);
 
        if (retval == PAM_NEW_AUTHTOK_REQD ||
            retval == PAM_AUTHTOK_EXPIRED) {
 
+               char *new_authtok_required_during_auth = NULL;
+
                if (!asprintf(&new_authtok_required, "%d", retval)) {
                        retval = PAM_BUF_ERR;
                        goto out;
@@ -1443,6 +1811,15 @@ int pam_sm_authenticate(pam_handle_t *pamh, int flags,
                pam_set_data(pamh, PAM_WINBIND_NEW_AUTHTOK_REQD, new_authtok_required, _pam_winbind_cleanup_func);
 
                retval = PAM_SUCCESS;
+
+               if (!asprintf(&new_authtok_required_during_auth, "%d", true)) {
+                       retval = PAM_BUF_ERR;
+                       goto out;
+               }
+
+               pam_set_data(pamh, PAM_WINBIND_NEW_AUTHTOK_REQD_DURING_AUTH, 
+                            new_authtok_required_during_auth, _pam_winbind_cleanup_func);
+
                goto out;
        }
 
@@ -1453,6 +1830,10 @@ out:
                free(username_ret);
        }
 
+       if ( real_username ) {          
+               free( real_username );
+       }       
+                       
        if (d) {
                iniparser_freedict(d);
        }
@@ -1461,6 +1842,10 @@ out:
                pam_set_data(pamh, PAM_WINBIND_NEW_AUTHTOK_REQD, NULL, NULL);
        }
 
+       if (retval != PAM_SUCCESS) {
+               _pam_free_data_info3(pamh);
+       }
+
        _PAM_LOG_FUNCTION_LEAVE("pam_sm_authenticate", pamh, ctrl, retval);
 
        return retval;
@@ -1718,6 +2103,49 @@ out:
        return retval;
 }
 
+/**
+ * evaluate whether we need to re-authenticate with kerberos after a password change
+ * 
+ * @param pamh PAM handle
+ * @param ctrl PAM winbind options.
+ * @param user The username
+ *
+ * @return boolean Returns true if required, false if not.
+ */
+
+static bool _pam_require_krb5_auth_after_chauthtok(pam_handle_t *pamh, int ctrl, const char *user)
+{
+
+       /* Make sure that we only do this if 
+        * a) the chauthtok got initiated during a logon attempt (authenticate->acct_mgmt->chauthtok)
+        * b) any later password change via the "passwd" command if done by the user itself 
+        */
+               
+       char *new_authtok_reqd_during_auth = NULL;
+       struct passwd *pwd = NULL;
+
+       if (!(ctrl & WINBIND_KRB5_AUTH)) {
+               return false;
+       }
+
+       _pam_get_data(pamh, PAM_WINBIND_NEW_AUTHTOK_REQD_DURING_AUTH, &new_authtok_reqd_during_auth);
+       pam_set_data(pamh, PAM_WINBIND_NEW_AUTHTOK_REQD_DURING_AUTH, NULL, NULL);
+
+       if (new_authtok_reqd_during_auth) {
+               return true;
+       }
+
+       pwd = getpwnam(user);
+       if (!pwd) {
+               return false;
+       }
+
+       if (getuid() == pwd->pw_uid) {
+               return true;
+       }
+
+       return false;
+}
 
 
 PAM_EXTERN 
@@ -1737,6 +2165,10 @@ int pam_sm_chauthtok(pam_handle_t * pamh, int flags,
        
        int retry = 0;
        dictionary *d = NULL;
+       char *username_ret = NULL;
+       struct winbindd_response response;
+
+       ZERO_STRUCT(response);
 
        ctrl = _pam_parse(pamh, flags, argc, argv, &d);
        if (ctrl == -1) {
@@ -1786,7 +2218,6 @@ int pam_sm_chauthtok(pam_handle_t * pamh, int flags,
         */
 
        if (flags & PAM_PRELIM_CHECK) {
-               struct winbindd_response response;
                time_t pwdlastset_prelim = 0;
                
                /* instruct user what is happening */
@@ -1812,33 +2243,18 @@ int pam_sm_chauthtok(pam_handle_t * pamh, int flags,
                        goto out;
                }
 
-               /* We don't need krb5 env set for password change test. */
-               ctrl &= ~WINBIND_KRB5_AUTH;
-
                /* verify that this is the password for this user */
                
                ret = winbind_auth_request(pamh, ctrl, user, pass_old,
-                                       NULL, NULL, &response, &pwdlastset_prelim, NULL);
+                                          NULL, NULL, 0, &response,
+                                          &pwdlastset_prelim, NULL);
 
                if (ret != PAM_ACCT_EXPIRED && 
                    ret != PAM_AUTHTOK_EXPIRED &&
                    ret != PAM_NEW_AUTHTOK_REQD &&
                    ret != PAM_SUCCESS) {
                        pass_old = NULL;
-                       if (d) {
-                               iniparser_freedict(d);
-                       }
-                       /* Deal with offline errors. */
-                       PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh,
-                                               response,
-                                               "NT_STATUS_NO_LOGON_SERVERS");
-                       PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh,
-                                               response,
-                                               "NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND");
-                       PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh,
-                                               response,
-                                               "NT_STATUS_ACCESS_DENIED");
-                       return ret;
+                       goto out;
                }
                
                pam_set_data(pamh, PAM_WINBIND_PWD_LAST_SET, (void *)pwdlastset_prelim, NULL);
@@ -1919,33 +2335,41 @@ int pam_sm_chauthtok(pam_handle_t * pamh, int flags,
                        goto out;
                }
 
-               /* just in case we need krb5 creds after a password change over msrpc */
-
-               if (ctrl & WINBIND_KRB5_AUTH) {
-                       struct winbindd_response response;
+               if (_pam_require_krb5_auth_after_chauthtok(pamh, ctrl, user)) {
 
                        const char *member = get_member_from_config(pamh, argc, argv, ctrl, d);
                        const char *cctype = get_krb5_cc_type_from_config(pamh, argc, argv, ctrl, d);
+                       const int warn_pwd_expire =
+                        get_warn_pwd_expire_from_config(pamh, argc, argv, ctrl,
+                                                        d);
 
                        ret = winbind_auth_request(pamh, ctrl, user, pass_new,
-                                                       member, cctype, &response, NULL, NULL);
+                                                  member, cctype, 0, &response,
+                                                  NULL, &username_ret);
                        _pam_overwrite(pass_new);
                        _pam_overwrite(pass_old);
                        pass_old = pass_new = NULL;
-                       if (d) {
-                               iniparser_freedict(d);
+
+                       if (ret == PAM_SUCCESS) {
+                       
+                               /* warn a user if the password is about to expire soon */
+                               _pam_warn_password_expiry(pamh, ctrl, &response,
+                                                         warn_pwd_expire , NULL);
+
+                               /* set some info3 info for other modules in the stack */
+                               _pam_set_data_info3(pamh, ctrl, &response);
+
+                               /* put krb5ccname into env */
+                               _pam_setup_krb5_env(pamh, ctrl, response.data.auth.krb5ccname);
+
+                               if (username_ret) {
+                                       pam_set_item (pamh, PAM_USER, username_ret);
+                                       _pam_log_debug(pamh, ctrl, LOG_INFO, "Returned user was '%s'", username_ret);
+                                       free(username_ret);
+                               }
                        }
-                       /* Deal with offline errors. */
-                       PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh,
-                                               response,
-                                               "NT_STATUS_NO_LOGON_SERVERS");
-                       PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh,
-                                               response,
-                                               "NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND");
-                       PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh,
-                                               response,
-                                               "NT_STATUS_ACCESS_DENIED");
-                       return ret;
+
+                       goto out;
                }
        } else {
                ret = PAM_SERVICE_ERR;
@@ -1956,6 +2380,11 @@ out:
                iniparser_freedict(d);
        }
 
+       /* Deal with offline errors. */
+       PAM_WB_REMARK_CHECK_RESPONSE(pamh, ctrl, response, "NT_STATUS_NO_LOGON_SERVERS");
+       PAM_WB_REMARK_CHECK_RESPONSE(pamh, ctrl, response, "NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND");
+       PAM_WB_REMARK_CHECK_RESPONSE(pamh, ctrl, response, "NT_STATUS_ACCESS_DENIED");
+
        _PAM_LOG_FUNCTION_LEAVE("pam_sm_chauthtok", pamh, ctrl, ret);
        
        return ret;