r21152: Correctly omit pam conversations when PAM_SILENT has been set by the
[ira/wip.git] / source3 / nsswitch / pam_winbind.c
1 /* pam_winbind module
2
3    Copyright Andrew Tridgell <tridge@samba.org> 2000
4    Copyright Tim Potter <tpot@samba.org> 2000
5    Copyright Andrew Bartlett <abartlet@samba.org> 2002
6    Copyright Guenther Deschner <gd@samba.org> 2005-2007
7
8    largely based on pam_userdb by Cristian Gafton <gafton@redhat.com> 
9    also contains large slabs of code from pam_unix by Elliot Lee <sopwith@redhat.com>
10    (see copyright below for full details)
11 */
12
13 #include "pam_winbind.h"
14
15 #define _PAM_LOG_FUNCTION_ENTER(function, pamh, ctrl, flags) \
16         do { \
17                 _pam_log_debug(pamh, ctrl, LOG_DEBUG, "[pamh: 0x%08x] ENTER: " function " (flags: 0x%04x)", (uint32) pamh, flags); \
18                 _pam_log_state(pamh, ctrl); \
19         } while (0)
20
21 #define _PAM_LOG_FUNCTION_LEAVE(function, pamh, ctrl, retval) \
22         do { \
23                 _pam_log_debug(pamh, ctrl, LOG_DEBUG, "[pamh: 0x%08x] LEAVE: " function " returning %d", (uint32) pamh, retval); \
24                 _pam_log_state(pamh, ctrl); \
25         } while (0)
26
27 /* data tokens */
28
29 #define MAX_PASSWD_TRIES        3
30
31 /*
32  * Work around the pam API that has functions with void ** as parameters.
33  * These lead to strict aliasing warnings with gcc.
34  */
35 static int _pam_get_item(const pam_handle_t *pamh, int item_type,
36                          const void *_item)
37 {
38         const void **item = (const void **)_item;
39         return pam_get_item(pamh, item_type, item);
40 }
41 static int _pam_get_data(const pam_handle_t *pamh,
42                          const char *module_data_name, const void *_data)
43 {
44         const void **data = (const void **)_data;
45         return pam_get_data(pamh, module_data_name, data);
46 }
47
48 /* some syslogging */
49
50 #ifdef HAVE_PAM_VSYSLOG
51 static void _pam_log_int(const pam_handle_t *pamh, int err, const char *format, va_list args)
52 {
53         pam_vsyslog(pamh, err, format, args);
54 }
55 #else
56 static void _pam_log_int(const pam_handle_t *pamh, int err, const char *format, va_list args)
57 {
58         char *format2 = NULL;
59         const char *service;
60
61         _pam_get_item(pamh, PAM_SERVICE, &service);
62
63         format2 = malloc(strlen(MODULE_NAME)+strlen(format)+strlen(service)+5);
64         if (format2 == NULL) {
65                 /* what else todo ? */
66                 vsyslog(err, format, args);
67                 return;
68         }
69
70         sprintf(format2, "%s(%s): %s", MODULE_NAME, service, format);
71         vsyslog(err, format2, args);
72         SAFE_FREE(format2);
73 }
74 #endif /* HAVE_PAM_VSYSLOG */
75
76 static BOOL _pam_log_is_silent(int ctrl)
77 {
78         return on(ctrl, WINBIND_SILENT);
79 }
80
81 static void _pam_log(const pam_handle_t *pamh, int ctrl, int err, const char *format, ...)
82 {
83         va_list args;
84
85         if (_pam_log_is_silent(ctrl)) {
86                 return;
87         }
88
89         va_start(args, format);
90         _pam_log_int(pamh, err, format, args);
91         va_end(args);
92 }
93
94 static BOOL _pam_log_is_debug_enabled(int ctrl)
95 {
96         if (ctrl == -1) {
97                 return False;
98         }
99
100         if (_pam_log_is_silent(ctrl)) {
101                 return False;
102         }
103
104         if (!(ctrl & WINBIND_DEBUG_ARG)) {
105                 return False;
106         }
107
108         return True;
109 }
110
111 static BOOL _pam_log_is_debug_state_enabled(int ctrl)
112 {
113         if (!(ctrl & WINBIND_DEBUG_STATE)) {
114                 return False;
115         }
116
117         return _pam_log_is_debug_enabled(ctrl);
118 }
119
120 static void _pam_log_debug(const pam_handle_t *pamh, int ctrl, int err, const char *format, ...)
121 {
122         va_list args;
123
124         if (!_pam_log_is_debug_enabled(ctrl)) {
125                 return;
126         }
127
128         va_start(args, format);
129         _pam_log_int(pamh, err, format, args);
130         va_end(args);
131 }
132
133 static void _pam_log_state_datum(const pam_handle_t *pamh, int ctrl, int item_type, const char *key, int is_string)
134 {
135         const void *data = NULL;
136         if (item_type != 0) {
137                 pam_get_item(pamh, item_type, &data);
138         } else {
139                 pam_get_data(pamh, key, &data);
140         }
141         if (data != NULL) {
142                 const char *type = (item_type != 0) ? "ITEM" : "DATA";
143                 if (is_string != 0) {
144                         _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);
145                 } else {
146                         _pam_log_debug(pamh, ctrl, LOG_DEBUG, "[pamh: 0x%08x] STATE: %s(%s) = 0x%08x", (uint32) pamh, type, key, (uint32) data);
147                 }
148         }
149 }
150
151 #define _PAM_LOG_STATE_DATA_POINTER(pamh, ctrl, module_data_name) \
152         _pam_log_state_datum(pamh, ctrl, 0, module_data_name, 0)
153
154 #define _PAM_LOG_STATE_DATA_STRING(pamh, ctrl, module_data_name) \
155         _pam_log_state_datum(pamh, ctrl, 0, module_data_name, 1)
156
157 #define _PAM_LOG_STATE_ITEM_POINTER(pamh, ctrl, item_type) \
158         _pam_log_state_datum(pamh, ctrl, item_type, #item_type, 0)
159
160 #define _PAM_LOG_STATE_ITEM_STRING(pamh, ctrl, item_type) \
161         _pam_log_state_datum(pamh, ctrl, item_type, #item_type, 1)
162
163 #ifdef DEBUG_PASSWORD
164 #define _LOG_PASSWORD_AS_STRING 1
165 #else
166 #define _LOG_PASSWORD_AS_STRING 0
167 #endif
168
169 #define _PAM_LOG_STATE_ITEM_PASSWORD(pamh, ctrl, item_type) \
170         _pam_log_state_datum(pamh, ctrl, item_type, #item_type, _LOG_PASSWORD_AS_STRING)
171
172 static void _pam_log_state(const pam_handle_t *pamh, int ctrl)
173 {
174         if (!_pam_log_is_debug_state_enabled(ctrl)) {
175                 return;
176         }
177
178         _PAM_LOG_STATE_ITEM_STRING(pamh, ctrl, PAM_SERVICE);
179         _PAM_LOG_STATE_ITEM_STRING(pamh, ctrl, PAM_USER);
180         _PAM_LOG_STATE_ITEM_STRING(pamh, ctrl, PAM_TTY);
181         _PAM_LOG_STATE_ITEM_STRING(pamh, ctrl, PAM_RHOST);
182         _PAM_LOG_STATE_ITEM_STRING(pamh, ctrl, PAM_RUSER);
183         _PAM_LOG_STATE_ITEM_PASSWORD(pamh, ctrl, PAM_OLDAUTHTOK);
184         _PAM_LOG_STATE_ITEM_PASSWORD(pamh, ctrl, PAM_AUTHTOK);
185         _PAM_LOG_STATE_ITEM_STRING(pamh, ctrl, PAM_USER_PROMPT);
186         _PAM_LOG_STATE_ITEM_POINTER(pamh, ctrl, PAM_CONV);
187 #ifdef PAM_FAIL_DELAY
188         _PAM_LOG_STATE_ITEM_POINTER(pamh, ctrl, PAM_FAIL_DELAY);
189 #endif
190 #ifdef PAM_REPOSITORY
191         _PAM_LOG_STATE_ITEM_POINTER(pamh, ctrl, PAM_REPOSITORY);
192 #endif
193
194         _PAM_LOG_STATE_DATA_STRING(pamh, ctrl, PAM_WINBIND_HOMEDIR);
195         _PAM_LOG_STATE_DATA_STRING(pamh, ctrl, PAM_WINBIND_LOGONSCRIPT);
196         _PAM_LOG_STATE_DATA_STRING(pamh, ctrl, PAM_WINBIND_PROFILEPATH);
197         _PAM_LOG_STATE_DATA_STRING(pamh, ctrl, PAM_WINBIND_NEW_AUTHTOK_REQD); /* Use atoi to get PAM result code */
198         _PAM_LOG_STATE_DATA_POINTER(pamh, ctrl, PAM_WINBIND_PWD_LAST_SET);
199 }
200
201 static int _pam_parse(const pam_handle_t *pamh, int flags, int argc, const char **argv, dictionary **result_d)
202 {
203         int ctrl = 0;
204         const char *config_file = NULL;
205         int i;
206         const char **v;
207         dictionary *d = NULL;
208
209         if (flags & PAM_SILENT) {
210                 ctrl |= WINBIND_SILENT;
211         }
212
213         for (i=argc,v=argv; i-- > 0; ++v) {
214                 if (!strncasecmp(*v, "config", strlen("config"))) {
215                         ctrl |= WINBIND_CONFIG_FILE;
216                         config_file = v[i];
217                         break;
218                 }
219         }
220
221         if (config_file == NULL) {
222                 config_file = PAM_WINBIND_CONFIG_FILE;
223         }
224
225         d = iniparser_load(config_file);
226         if (d == NULL) {
227                 goto config_from_pam;
228         }
229
230         if (iniparser_getboolean(d, "global:debug", False)) {
231                 ctrl |= WINBIND_DEBUG_ARG;
232         }
233
234         if (iniparser_getboolean(d, "global:debug_state", False)) {
235                 ctrl |= WINBIND_DEBUG_STATE;
236         }
237
238         if (iniparser_getboolean(d, "global:cached_login", False)) {
239                 ctrl |= WINBIND_CACHED_LOGIN;
240         }
241
242         if (iniparser_getboolean(d, "global:krb5_auth", False)) {
243                 ctrl |= WINBIND_KRB5_AUTH;
244         }
245
246         if (iniparser_getboolean(d, "global:silent", False)) {
247                 ctrl |= WINBIND_SILENT;
248         }
249
250         if (iniparser_getstr(d, "global:krb5_ccache_type") != NULL) {
251                 ctrl |= WINBIND_KRB5_CCACHE_TYPE;
252         }
253
254         if ((iniparser_getstr(d, "global:require-membership-of") != NULL) ||
255             (iniparser_getstr(d, "global:require_membership_of") != NULL)) {
256                 ctrl |= WINBIND_REQUIRED_MEMBERSHIP;
257         }
258
259         if (iniparser_getboolean(d, "global:try_first_pass", False)) {
260                 ctrl |= WINBIND_TRY_FIRST_PASS_ARG;
261         }
262
263 config_from_pam:
264         /* step through arguments */
265         for (i=argc,v=argv; i-- > 0; ++v) {
266
267                 /* generic options */
268                 if (!strcmp(*v,"debug"))
269                         ctrl |= WINBIND_DEBUG_ARG;
270                 else if (!strcasecmp(*v, "debug_state"))
271                         ctrl |= WINBIND_DEBUG_STATE;
272                 else if (!strcasecmp(*v, "use_authtok"))
273                         ctrl |= WINBIND_USE_AUTHTOK_ARG;
274                 else if (!strcasecmp(*v, "use_first_pass"))
275                         ctrl |= WINBIND_USE_FIRST_PASS_ARG;
276                 else if (!strcasecmp(*v, "try_first_pass"))
277                         ctrl |= WINBIND_TRY_FIRST_PASS_ARG;
278                 else if (!strcasecmp(*v, "unknown_ok"))
279                         ctrl |= WINBIND_UNKNOWN_OK_ARG;
280                 else if (!strncasecmp(*v, "require_membership_of", strlen("require_membership_of")))
281                         ctrl |= WINBIND_REQUIRED_MEMBERSHIP;
282                 else if (!strncasecmp(*v, "require-membership-of", strlen("require-membership-of")))
283                         ctrl |= WINBIND_REQUIRED_MEMBERSHIP;
284                 else if (!strcasecmp(*v, "krb5_auth"))
285                         ctrl |= WINBIND_KRB5_AUTH;
286                 else if (!strncasecmp(*v, "krb5_ccache_type", strlen("krb5_ccache_type")))
287                         ctrl |= WINBIND_KRB5_CCACHE_TYPE;
288                 else if (!strcasecmp(*v, "cached_login"))
289                         ctrl |= WINBIND_CACHED_LOGIN;
290                 else {
291                         _pam_log(pamh, ctrl, LOG_ERR, "pam_parse: unknown option: %s", *v);
292                         return -1;
293                 }
294
295         }
296
297         if (result_d) {
298                 *result_d = d;
299         } else {
300                 if (d) {
301                         iniparser_freedict(d);
302                 }
303         }
304
305         return ctrl;
306 };
307
308 static void _pam_winbind_cleanup_func(pam_handle_t *pamh, void *data, int error_status)
309 {
310         int ctrl = _pam_parse(pamh, 0, 0, NULL, NULL);
311         if (_pam_log_is_debug_state_enabled(ctrl)) {
312                 _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);
313         }
314         SAFE_FREE(data);
315 }
316
317
318 static const struct ntstatus_errors {
319         const char *ntstatus_string;
320         const char *error_string;
321 } ntstatus_errors[] = {
322         {"NT_STATUS_OK", "Success"},
323         {"NT_STATUS_BACKUP_CONTROLLER", "No primary Domain Controler available"},
324         {"NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND", "No domain controllers found"},
325         {"NT_STATUS_NO_LOGON_SERVERS", "No logon servers"},
326         {"NT_STATUS_PWD_TOO_SHORT", "Password too short"},
327         {"NT_STATUS_PWD_TOO_RECENT", "The password of this user is too recent to change"},
328         {"NT_STATUS_PWD_HISTORY_CONFLICT", "Password is already in password history"},
329         {"NT_STATUS_PASSWORD_EXPIRED", "Your password has expired"},
330         {"NT_STATUS_PASSWORD_MUST_CHANGE", "You need to change your password now"},
331         {"NT_STATUS_INVALID_WORKSTATION", "You are not allowed to logon from this workstation"},
332         {"NT_STATUS_INVALID_LOGON_HOURS", "You are not allowed to logon at this time"},
333         {"NT_STATUS_ACCOUNT_EXPIRED", "Your account has expired. Please contact your System administrator"}, /* SCNR */
334         {"NT_STATUS_ACCOUNT_DISABLED", "Your account is disabled. Please contact your System administrator"}, /* SCNR */
335         {"NT_STATUS_ACCOUNT_LOCKED_OUT", "Your account has been locked. Please contact your System administrator"}, /* SCNR */
336         {"NT_STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT", "Invalid Trust Account"},
337         {"NT_STATUS_NOLOGON_SERVER_TRUST_ACCOUNT", "Invalid Trust Account"},
338         {"NT_STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT", "Invalid Trust Account"},
339         {"NT_STATUS_ACCESS_DENIED", "Access is denied"},
340         {NULL, NULL}
341 };
342
343 const char *_get_ntstatus_error_string(const char *nt_status_string) 
344 {
345         int i;
346         for (i=0; ntstatus_errors[i].ntstatus_string != NULL; i++) {
347                 if (!strcasecmp(ntstatus_errors[i].ntstatus_string, nt_status_string)) {
348                         return ntstatus_errors[i].error_string;
349                 }
350         }
351         return NULL;
352 }
353
354 /* --- authentication management functions --- */
355
356 /* Attempt a conversation */
357
358 static int converse(pam_handle_t *pamh, int nargs,
359                     struct pam_message **message,
360                     struct pam_response **response)
361 {
362         int retval;
363         struct pam_conv *conv;
364
365         retval = _pam_get_item(pamh, PAM_CONV, &conv );
366         if (retval == PAM_SUCCESS) {
367                 retval = conv->conv(nargs, (const struct pam_message **)message,
368                                     response, conv->appdata_ptr);
369         }
370         
371         return retval; /* propagate error status */
372 }
373
374
375 static int _make_remark(pam_handle_t * pamh, int flags, int type, const char *text)
376 {
377         int retval = PAM_SUCCESS;
378
379         struct pam_message *pmsg[1], msg[1];
380         struct pam_response *resp;
381         
382         if (flags & WINBIND_SILENT) {
383                 return PAM_SUCCESS;
384         }
385
386         pmsg[0] = &msg[0];
387         msg[0].msg = CONST_DISCARD(char *, text);
388         msg[0].msg_style = type;
389         
390         resp = NULL;
391         retval = converse(pamh, 1, pmsg, &resp);
392         
393         if (resp) {
394                 _pam_drop_reply(resp, 1);
395         }
396         return retval;
397 }
398
399 static int _make_remark_v(pam_handle_t * pamh, int flags, int type, const char *format, va_list args)
400 {
401         char *var;
402         int ret;
403
404         ret = vasprintf(&var, format, args);
405         if (ret < 0) {
406                 _pam_log(pamh, 0, LOG_ERR, "memory allocation failure");
407                 return ret;
408         }
409
410         ret = _make_remark(pamh, flags, type, var);
411         SAFE_FREE(var);
412         return ret;
413 }
414
415 static int _make_remark_format(pam_handle_t * pamh, int flags, int type, const char *format, ...)
416 {
417         int ret;
418         va_list args;
419
420         va_start(args, format);
421         ret = _make_remark_v(pamh, flags, type, format, args);
422         va_end(args);
423         return ret;
424 }
425
426 static int pam_winbind_request(pam_handle_t * pamh, int ctrl,
427                                enum winbindd_cmd req_type,
428                                struct winbindd_request *request,
429                                struct winbindd_response *response)
430 {
431         /* Fill in request and send down pipe */
432         init_request(request, req_type);
433         
434         if (write_sock(request, sizeof(*request), 0) == -1) {
435                 _pam_log(pamh, ctrl, LOG_ERR, "pam_winbind_request: write to socket failed!");
436                 close_sock();
437                 return PAM_SERVICE_ERR;
438         }
439         
440         /* Wait for reply */
441         if (read_reply(response) == -1) {
442                 _pam_log(pamh, ctrl, LOG_ERR, "pam_winbind_request: read from socket failed!");
443                 close_sock();
444                 return PAM_SERVICE_ERR;
445         }
446
447         /* We are done with the socket - close it and avoid mischeif */
448         close_sock();
449
450         /* Copy reply data from socket */
451         if (response->result == WINBINDD_OK) {
452                 return PAM_SUCCESS;
453         }
454
455         /* no need to check for pam_error codes for getpwnam() */
456         switch (req_type) {
457
458                 case WINBINDD_GETPWNAM:
459                 case WINBINDD_LOOKUPNAME:
460                         _pam_log(pamh, ctrl, LOG_ERR, "request failed: %s, NT error was %s", 
461                                 response->data.auth.nt_status_string);
462                         return PAM_USER_UNKNOWN;
463                 default:
464                         break;
465         }
466
467         if (response->data.auth.pam_error != PAM_SUCCESS) {
468                 _pam_log(pamh, ctrl, LOG_ERR, "request failed: %s, PAM error was %s (%d), NT error was %s", 
469                          response->data.auth.error_string,
470                          pam_strerror(pamh, response->data.auth.pam_error),
471                          response->data.auth.pam_error,
472                          response->data.auth.nt_status_string);
473                 return response->data.auth.pam_error;
474         } 
475         
476         _pam_log(pamh, ctrl, LOG_ERR, "request failed, but PAM error 0!");
477
478         return PAM_SERVICE_ERR;
479 }
480
481 static int pam_winbind_request_log(pam_handle_t * pamh,
482                                    int ctrl,
483                                    enum winbindd_cmd req_type,
484                                    struct winbindd_request *request,
485                                    struct winbindd_response *response,
486                                    const char *user)
487 {
488         int retval;
489
490         retval = pam_winbind_request(pamh, ctrl, req_type, request, response);
491
492         switch (retval) {
493         case PAM_AUTH_ERR:
494                 /* incorrect password */
495                 _pam_log(pamh, ctrl, LOG_WARNING, "user '%s' denied access (incorrect password or invalid membership)", user);
496                 return retval;
497         case PAM_ACCT_EXPIRED:
498                 /* account expired */
499                 _pam_log(pamh, ctrl, LOG_WARNING, "user '%s' account expired", user);
500                 return retval;
501         case PAM_AUTHTOK_EXPIRED:
502                 /* password expired */
503                 _pam_log(pamh, ctrl, LOG_WARNING, "user '%s' password expired", user);
504                 return retval;
505         case PAM_NEW_AUTHTOK_REQD:
506                 /* new password required */
507                 _pam_log(pamh, ctrl, LOG_WARNING, "user '%s' new password required", user);
508                 return retval;
509         case PAM_USER_UNKNOWN:
510                 /* the user does not exist */
511                 _pam_log_debug(pamh, ctrl, LOG_NOTICE, "user '%s' not found", user);
512                 if (ctrl & WINBIND_UNKNOWN_OK_ARG) {
513                         return PAM_IGNORE;
514                 }        
515                 return retval;
516         case PAM_SUCCESS:
517                 if (req_type == WINBINDD_PAM_AUTH) {
518                         /* Otherwise, the authentication looked good */
519                         _pam_log(pamh, ctrl, LOG_NOTICE, "user '%s' granted access", user);
520                 } else if (req_type == WINBINDD_PAM_CHAUTHTOK) {
521                         /* Otherwise, the authentication looked good */
522                         _pam_log(pamh, ctrl, LOG_NOTICE, "user '%s' password changed", user);
523                 } else { 
524                         /* Otherwise, the authentication looked good */
525                         _pam_log(pamh, ctrl, LOG_NOTICE, "user '%s' OK", user);
526                 }
527         
528                 return retval;
529         default:
530                 /* we don't know anything about this return value */
531                 _pam_log(pamh, ctrl, LOG_ERR, "internal module error (retval = %d, user = '%s')",
532                          retval, user);
533                 return retval;
534         }
535 }
536
537 static BOOL _pam_send_password_expiry_message(pam_handle_t *pamh, int ctrl, time_t next_change, time_t now) 
538 {
539         int days = 0;
540         struct tm tm_now, tm_next_change;
541
542         if ((next_change < 0) ||
543             (next_change < now) ||
544             (next_change > now + DAYS_TO_WARN_BEFORE_PWD_EXPIRES * SECONDS_PER_DAY)) {
545                 return False;
546         }
547
548         if ((localtime_r(&now, &tm_now) == NULL) || 
549             (localtime_r(&next_change, &tm_next_change) == NULL)) {
550                 return False;
551         }
552
553         days = (tm_next_change.tm_yday+tm_next_change.tm_year*365) - (tm_now.tm_yday+tm_now.tm_year*365);
554
555         if (days == 0) {
556                 _make_remark(pamh, ctrl, PAM_TEXT_INFO, "Your password expires today");
557                 return True;
558         } 
559         
560         if (days > 0 && days < DAYS_TO_WARN_BEFORE_PWD_EXPIRES) {
561                 _make_remark_format(pamh, ctrl, PAM_TEXT_INFO, "Your password will expire in %d %s", 
562                         days, (days > 1) ? "days":"day");
563                 return True;
564         }
565
566         return False;
567 }
568
569 static void _pam_warn_password_expires_in_future(pam_handle_t *pamh, int ctrl, struct winbindd_response *response)
570 {
571         time_t now = time(NULL);
572         time_t next_change = 0;
573
574         /* accounts with ACB_PWNOEXP set never receive a warning */
575         if (response->data.auth.info3.acct_flags & ACB_PWNOEXP) {
576                 return;
577         }
578
579         /* no point in sending a warning if this is a grace logon */
580         if (PAM_WB_GRACE_LOGON(response->data.auth.info3.user_flgs)) {
581                 return;
582         }
583
584         /* check if the info3 must change timestamp has been set */
585         next_change = response->data.auth.info3.pass_must_change_time;
586
587         if (_pam_send_password_expiry_message(pamh, ctrl, next_change, now)) {
588                 return;
589         }
590
591         /* now check for the global password policy */
592         if (response->data.auth.policy.expire <= 0) {
593                 return;
594         }
595
596         next_change = response->data.auth.info3.pass_last_set_time + 
597                       response->data.auth.policy.expire;
598
599         if (_pam_send_password_expiry_message(pamh, ctrl, next_change, now)) {
600                 return;
601         }
602
603         /* no warning sent */
604 }
605
606 #define IS_SID_STRING(name) (strncmp("S-", name, 2) == 0)
607
608 static BOOL safe_append_string(char *dest,
609                         const char *src,
610                         int dest_buffer_size)
611 /**
612  * Append a string, making sure not to overflow and to always return a NULL-terminated
613  * string.
614  *
615  * @param dest Destination string buffer (must already be NULL-terminated).
616  * @param src Source string buffer.
617  * @param dest_buffer_size Size of dest buffer in bytes.
618  *
619  * @return False if dest buffer is not big enough (no bytes copied), True on success.
620  */
621 {
622         int dest_length = strlen(dest);
623         int src_length = strlen(src);
624
625         if ( dest_length + src_length + 1 > dest_buffer_size ) {
626                 return False;
627         }
628
629         memcpy(dest + dest_length, src, src_length + 1);
630         return True;
631 }
632
633 static BOOL winbind_name_to_sid_string(pam_handle_t *pamh,
634                                 int ctrl,
635                                 const char *user,
636                                 const char *name,
637                                 char *sid_list_buffer,
638                                 int sid_list_buffer_size)
639 /**
640  * Convert a names into a SID string, appending it to a buffer.
641  *
642  * @param pamh PAM handle
643  * @param ctrl PAM winbind options.
644  * @param user User in PAM request.
645  * @param name Name to convert.
646  * @param sid_list_buffer Where to append the string sid.
647  * @param sid_list_buffer Size of sid_list_buffer (in bytes).
648  *
649  * @return False on failure, True on success.
650  */
651 {
652         const char* sid_string;
653         struct winbindd_response sid_response;
654
655         /* lookup name? */ 
656         if (IS_SID_STRING(name)) {
657                 sid_string = name;
658         } else {
659                 struct winbindd_request sid_request;
660
661                 ZERO_STRUCT(sid_request);
662                 ZERO_STRUCT(sid_response);
663
664                 _pam_log_debug(pamh, ctrl, LOG_DEBUG, "no sid given, looking up: %s\n", name);
665
666                 /* fortunatly winbindd can handle non-separated names */
667                 strncpy(sid_request.data.name.name, name,
668                         sizeof(sid_request.data.name.name) - 1);
669
670                 if (pam_winbind_request_log(pamh, ctrl, WINBINDD_LOOKUPNAME, &sid_request, &sid_response, user)) {
671                         _pam_log(pamh, ctrl, LOG_INFO, "could not lookup name: %s\n", name); 
672                         return False;
673                 }
674
675                 sid_string = sid_response.data.sid.sid;
676         }
677
678         if (!safe_append_string(sid_list_buffer, sid_string, sid_list_buffer_size)) {
679                 return False;
680         }
681
682         return True;
683 }
684
685 static BOOL winbind_name_list_to_sid_string_list(pam_handle_t *pamh,
686                                 int ctrl,
687                                 const char *user,
688                                 const char *name_list,
689                                 char *sid_list_buffer,
690                                 int sid_list_buffer_size)
691 /**
692  * Convert a list of names into a list of sids.
693  *
694  * @param pamh PAM handle
695  * @param ctrl PAM winbind options.
696  * @param user User in PAM request.
697  * @param name_list List of names or string sids, separated by commas.
698  * @param sid_list_buffer Where to put the list of string sids.
699  * @param sid_list_buffer Size of sid_list_buffer (in bytes).
700  *
701  * @return False on failure, True on success.
702  */
703 {
704         BOOL result = False;
705         char *current_name = NULL;
706         const char *search_location;
707         const char *comma;
708
709         if ( sid_list_buffer_size > 0 ) {
710                 sid_list_buffer[0] = 0;
711         }
712
713         search_location = name_list;
714         while ( (comma = strstr(search_location, ",")) != NULL ) {
715                 current_name = strndup(search_location, comma - search_location);
716                 if (NULL == current_name) {
717                         goto out;
718                 }
719
720                 if (!winbind_name_to_sid_string(pamh, ctrl, user, current_name, sid_list_buffer, sid_list_buffer_size)) {
721                         goto out;
722                 }
723
724                 SAFE_FREE(current_name);
725
726                 if (!safe_append_string(sid_list_buffer, ",", sid_list_buffer_size)) {
727                         goto out;
728                 }
729
730                 search_location = comma + 1;
731         }
732
733         if (!winbind_name_to_sid_string(pamh, ctrl, user, search_location, sid_list_buffer, sid_list_buffer_size)) {
734                 goto out;
735         }
736
737         result = True;
738
739 out:
740         SAFE_FREE(current_name);
741         return result;
742 }
743
744 /**
745  * Compose Password Restriction String for a PAM_ERROR_MSG conversation.
746  *
747  * @param response The struct winbindd_response.
748  *
749  * @return string (caller needs to free).
750  */
751
752 static char *_pam_compose_pwd_restriction_string(struct winbindd_response *response)
753 {
754         char *str = NULL;
755         size_t offset = 0, ret = 0, str_size = 1024;
756
757         str = (char *)malloc(str_size);
758         if (!str) {
759                 return NULL;
760         }
761
762         memset(str, '\0', str_size);
763
764         offset = snprintf(str, str_size, "Your password ");
765         if (offset == -1) {
766                 goto failed;
767         }
768
769         if (response->data.auth.policy.min_length_password > 0) {
770                 ret = snprintf(str+offset, str_size-offset,
771                              "must be at least %d characters; ",
772                              response->data.auth.policy.min_length_password);
773                 if (ret == -1) {
774                         goto failed;
775                 }
776                 offset += ret;
777         }
778         
779         if (response->data.auth.policy.password_history > 0) {
780                 ret = snprintf(str+offset, str_size-offset,
781                              "cannot repeat any of your previous %d passwords; ",
782                              response->data.auth.policy.password_history);
783                 if (ret == -1) {
784                         goto failed;
785                 }
786                 offset += ret;
787         }
788         
789         if (response->data.auth.policy.password_properties & DOMAIN_PASSWORD_COMPLEX) {
790                 ret = snprintf(str+offset, str_size-offset,
791                              "must contain capitals, numerals or punctuation; "
792                              "and cannot contain your account or full name; ");
793                 if (ret == -1) {
794                         goto failed;
795                 }
796                 offset += ret;
797         }
798
799         ret = snprintf(str+offset, str_size-offset, 
800                      "Please type a different password. "
801                      "Type a password which meets these requirements in both text boxes.");
802         if (ret == -1) {
803                 goto failed;
804         }
805
806         return str;
807
808  failed:
809         SAFE_FREE(str);
810         return NULL;
811 }
812
813 /* talk to winbindd */
814 static int winbind_auth_request(pam_handle_t * pamh,
815                                 int ctrl, 
816                                 const char *user, 
817                                 const char *pass, 
818                                 const char *member, 
819                                 const char *cctype,
820                                 struct winbindd_response *p_response,
821                                 time_t *pwd_last_set,
822                                 char **user_ret)
823 {
824         struct winbindd_request request;
825         struct winbindd_response response;
826         int ret;
827
828         ZERO_STRUCT(request);
829         ZERO_STRUCT(response);
830
831         if (pwd_last_set) {
832                 *pwd_last_set = 0;
833         }
834
835         strncpy(request.data.auth.user, user, 
836                 sizeof(request.data.auth.user)-1);
837
838         strncpy(request.data.auth.pass, pass, 
839                 sizeof(request.data.auth.pass)-1);
840
841         request.data.auth.krb5_cc_type[0] = '\0';
842         request.data.auth.uid = -1;
843         
844         request.flags = WBFLAG_PAM_INFO3_TEXT | WBFLAG_PAM_CONTACT_TRUSTDOM;
845
846         if (ctrl & WINBIND_KRB5_AUTH) {
847
848                 struct passwd *pwd = NULL;
849
850                 _pam_log_debug(pamh, ctrl, LOG_DEBUG, "enabling krb5 login flag\n"); 
851
852                 request.flags |= WBFLAG_PAM_KRB5 | WBFLAG_PAM_FALLBACK_AFTER_KRB5;
853
854                 pwd = getpwnam(user);
855                 if (pwd == NULL) {
856                         return PAM_USER_UNKNOWN;
857                 }
858                 request.data.auth.uid = pwd->pw_uid;
859         }
860
861         if (ctrl & WINBIND_CACHED_LOGIN) {
862                 _pam_log_debug(pamh, ctrl, LOG_DEBUG, "enabling cached login flag\n"); 
863                 request.flags |= WBFLAG_PAM_CACHED_LOGIN;
864         }
865
866         if (user_ret) {
867                 *user_ret = NULL;
868                 request.flags |= WBFLAG_PAM_UNIX_NAME;
869         }
870
871         if (cctype != NULL) {
872                 strncpy(request.data.auth.krb5_cc_type, cctype, 
873                         sizeof(request.data.auth.krb5_cc_type) - 1);
874                 _pam_log_debug(pamh, ctrl, LOG_DEBUG, "enabling request for a %s krb5 ccache\n", cctype); 
875         }
876
877         request.data.auth.require_membership_of_sid[0] = '\0';
878
879         if (member != NULL) {
880
881                 if (!winbind_name_list_to_sid_string_list(pamh, ctrl, user, member,
882                         request.data.auth.require_membership_of_sid,
883                         sizeof(request.data.auth.require_membership_of_sid))) {
884
885                         _pam_log_debug(pamh, ctrl, LOG_ERR, "failed to serialize membership of sid \"%s\"\n", member);
886                         return PAM_AUTH_ERR;
887                 }
888         }
889
890         ret = pam_winbind_request_log(pamh, ctrl, WINBINDD_PAM_AUTH, &request, &response, user);
891
892         if (pwd_last_set) {
893                 *pwd_last_set = response.data.auth.info3.pass_last_set_time;
894         }
895
896         if ((ctrl & WINBIND_KRB5_AUTH) && 
897             response.data.auth.krb5ccname[0] != '\0') {
898
899                 char var[PATH_MAX];
900
901                 _pam_log_debug(pamh, ctrl, LOG_DEBUG, "request returned KRB5CCNAME: %s", 
902                                response.data.auth.krb5ccname);
903         
904                 snprintf(var, sizeof(var), "KRB5CCNAME=%s", response.data.auth.krb5ccname);
905         
906                 ret = pam_putenv(pamh, var);
907                 if (ret != PAM_SUCCESS) {
908                         _pam_log(pamh, ctrl, LOG_ERR, "failed to set KRB5CCNAME to %s", var);
909                         return ret;
910                 }
911         }
912
913         if (p_response) {
914                 /* We want to process the response in the caller. */
915                 *p_response = response;
916                 return ret;
917         }
918
919         if (ret) {
920                 PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_PASSWORD_EXPIRED");
921                 PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_PASSWORD_MUST_CHANGE");
922                 PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_INVALID_WORKSTATION");
923                 PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_INVALID_LOGON_HOURS");
924                 PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_ACCOUNT_EXPIRED");
925                 PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_ACCOUNT_DISABLED");
926                 PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_ACCOUNT_LOCKED_OUT");
927                 PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT");
928                 PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_NOLOGON_SERVER_TRUST_ACCOUNT");
929                 PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT");
930                 PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND");
931                 PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_NO_LOGON_SERVERS");
932         }
933
934         /* handle the case where the auth was ok, but the password must expire right now */
935         /* good catch from Ralf Haferkamp: an expiry of "never" is translated to -1 */
936         if ( ! (response.data.auth.info3.acct_flags & ACB_PWNOEXP) &&
937              ! (PAM_WB_GRACE_LOGON(response.data.auth.info3.user_flgs)) &&
938             (response.data.auth.policy.expire > 0) && 
939             (response.data.auth.info3.pass_last_set_time + response.data.auth.policy.expire < time(NULL))) {
940
941                 ret = PAM_AUTHTOK_EXPIRED;
942
943                 _pam_log_debug(pamh, ctrl, LOG_DEBUG,"Password has expired (Password was last set: %d, "
944                                "the policy says it should expire here %d (now it's: %d)\n",
945                                response.data.auth.info3.pass_last_set_time,
946                                response.data.auth.info3.pass_last_set_time + response.data.auth.policy.expire,
947                                time(NULL));
948
949                 PAM_WB_REMARK_DIRECT_RET(pamh, ctrl, "NT_STATUS_PASSWORD_EXPIRED");
950
951         }
952
953         /* warn a user if the password is about to expire soon */
954         _pam_warn_password_expires_in_future(pamh, ctrl, &response);
955
956         /* inform about logon type */
957         if (PAM_WB_GRACE_LOGON(response.data.auth.info3.user_flgs)) {
958
959                 _make_remark(pamh, ctrl, PAM_ERROR_MSG, 
960                         "Grace login. Please change your password as soon you're online again");
961                 _pam_log_debug(pamh, ctrl, LOG_DEBUG,
962                         "User %s logged on using grace logon\n", user);
963
964         } else if (PAM_WB_CACHED_LOGON(response.data.auth.info3.user_flgs)) {
965
966                 _make_remark(pamh, ctrl, PAM_ERROR_MSG, 
967                         "Logging on using cached account. Network resources can be unavailable");
968                 _pam_log_debug(pamh, ctrl, LOG_DEBUG,
969                         "User %s logged on using cached account\n", user);
970         }
971
972         /* save the CIFS homedir for pam_cifs / pam_mount */
973         if (response.data.auth.info3.home_dir[0] != '\0') {
974
975                 int ret2 = pam_set_data(pamh, PAM_WINBIND_HOMEDIR,
976                                         (void *) strdup(response.data.auth.info3.home_dir),
977                                         _pam_winbind_cleanup_func);
978                 if (ret2) {
979                         _pam_log_debug(pamh, ctrl, LOG_DEBUG, "Could not set data: %s", 
980                                        pam_strerror(pamh, ret2));
981                 }
982
983         }
984
985         /* save the logon script path for other PAM modules */
986         if (response.data.auth.info3.logon_script[0] != '\0') {
987
988                 int ret2 = pam_set_data(pamh, PAM_WINBIND_LOGONSCRIPT, 
989                                         (void *) strdup(response.data.auth.info3.logon_script), 
990                                         _pam_winbind_cleanup_func);
991                 if (ret2) {
992                         _pam_log_debug(pamh, ctrl, LOG_DEBUG, "Could not set data: %s", 
993                                        pam_strerror(pamh, ret2));
994                 }
995         }
996
997         /* save the profile path for other PAM modules */
998         if (response.data.auth.info3.profile_path[0] != '\0') {
999
1000                 int ret2 = pam_set_data(pamh, PAM_WINBIND_PROFILEPATH, 
1001                                         (void *) strdup(response.data.auth.info3.profile_path), 
1002                                         _pam_winbind_cleanup_func);
1003                 if (ret2) {
1004                         _pam_log_debug(pamh, ctrl, LOG_DEBUG, "Could not set data: %s", 
1005                                        pam_strerror(pamh, ret2));
1006                 }
1007         }
1008
1009         /* If winbindd returned a username, return the pointer to it here. */
1010         if (user_ret && response.extra_data.data) {
1011                 /* We have to trust it's a null terminated string. */
1012                 *user_ret = (char *)response.extra_data.data;
1013         }
1014
1015         return ret;
1016 }
1017
1018 /* talk to winbindd */
1019 static int winbind_chauthtok_request(pam_handle_t * pamh,
1020                                      int ctrl,
1021                                      const char *user, 
1022                                      const char *oldpass,
1023                                      const char *newpass,
1024                                      time_t pwd_last_set) 
1025 {
1026         struct winbindd_request request;
1027         struct winbindd_response response;
1028         int ret;
1029
1030         ZERO_STRUCT(request);
1031         ZERO_STRUCT(response);
1032
1033         if (request.data.chauthtok.user == NULL) return -2;
1034
1035         strncpy(request.data.chauthtok.user, user, 
1036                 sizeof(request.data.chauthtok.user) - 1);
1037
1038         if (oldpass != NULL) {
1039                 strncpy(request.data.chauthtok.oldpass, oldpass, 
1040                         sizeof(request.data.chauthtok.oldpass) - 1);
1041         } else {
1042                 request.data.chauthtok.oldpass[0] = '\0';
1043         }
1044         
1045         if (newpass != NULL) {
1046                 strncpy(request.data.chauthtok.newpass, newpass, 
1047                         sizeof(request.data.chauthtok.newpass) - 1);
1048         } else {
1049                 request.data.chauthtok.newpass[0] = '\0';
1050         }
1051
1052         if (ctrl & WINBIND_KRB5_AUTH) {
1053                 request.flags = WBFLAG_PAM_KRB5 | WBFLAG_PAM_CONTACT_TRUSTDOM;
1054         }
1055
1056         ret = pam_winbind_request_log(pamh, ctrl, WINBINDD_PAM_CHAUTHTOK, &request, &response, user);
1057
1058         if (ret == PAM_SUCCESS) {
1059                 return ret;
1060         }
1061
1062         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_BACKUP_CONTROLLER");
1063         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND");
1064         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_NO_LOGON_SERVERS");
1065         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_ACCESS_DENIED");
1066
1067         /* TODO: tell the min pwd length ? */
1068         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_PWD_TOO_SHORT");
1069
1070         /* TODO: tell the minage ? */
1071         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_PWD_TOO_RECENT");
1072
1073         /* TODO: tell the history length ? */
1074         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl, response, "NT_STATUS_PWD_HISTORY_CONFLICT");
1075
1076         if (!strcasecmp(response.data.auth.nt_status_string, "NT_STATUS_PASSWORD_RESTRICTION")) {
1077
1078                 char *pwd_restriction_string = NULL;
1079
1080                 /* FIXME: avoid to send multiple PAM messages after another */
1081                 switch (response.data.auth.reject_reason) {
1082                         case -1:
1083                                 break;
1084                         case REJECT_REASON_OTHER:
1085                                 if ((response.data.auth.policy.min_passwordage > 0) &&
1086                                     (pwd_last_set + response.data.auth.policy.min_passwordage > time(NULL))) {
1087                                         PAM_WB_REMARK_DIRECT(pamh, ctrl, "NT_STATUS_PWD_TOO_RECENT");
1088                                 }
1089                                 break;
1090                         case REJECT_REASON_TOO_SHORT:
1091                                 PAM_WB_REMARK_DIRECT(pamh, ctrl, "NT_STATUS_PWD_TOO_SHORT");
1092                                 break;
1093                         case REJECT_REASON_IN_HISTORY:
1094                                 PAM_WB_REMARK_DIRECT(pamh, ctrl, "NT_STATUS_PWD_HISTORY_CONFLICT");
1095                                 break;
1096                         case REJECT_REASON_NOT_COMPLEX:
1097                                 _make_remark(pamh, ctrl, PAM_ERROR_MSG, "Password does not meet complexity requirements");
1098                                 break;
1099                         default:
1100                                 _pam_log_debug(pamh, ctrl, LOG_DEBUG,
1101                                                "unknown password change reject reason: %d", 
1102                                                response.data.auth.reject_reason);
1103                                 break;
1104                 }
1105
1106                 pwd_restriction_string = _pam_compose_pwd_restriction_string(&response);
1107                 if (pwd_restriction_string) {
1108                         _make_remark(pamh, ctrl, PAM_ERROR_MSG, pwd_restriction_string);
1109                         SAFE_FREE(pwd_restriction_string);
1110                 }
1111         }
1112
1113         return ret;
1114 }
1115
1116 /*
1117  * Checks if a user has an account
1118  *
1119  * return values:
1120  *       1  = User not found
1121  *       0  = OK
1122  *      -1  = System error
1123  */
1124 static int valid_user(pam_handle_t *pamh, int ctrl, const char *user)
1125 {
1126         /* check not only if the user is available over NSS calls, also make
1127          * sure it's really a winbind user, this is important when stacking PAM
1128          * modules in the 'account' or 'password' facility. */
1129
1130         struct passwd *pwd = NULL;
1131         struct winbindd_request request;
1132         struct winbindd_response response;
1133         int ret;
1134
1135         ZERO_STRUCT(request);
1136         ZERO_STRUCT(response);
1137
1138         pwd = getpwnam(user);
1139         if (pwd == NULL) {
1140                 return 1;
1141         }
1142
1143         strncpy(request.data.username, user,
1144                 sizeof(request.data.username) - 1);
1145
1146         ret = pam_winbind_request_log(pamh, ctrl, WINBINDD_GETPWNAM, &request, &response, user);
1147
1148         switch (ret) {
1149                 case PAM_USER_UNKNOWN:
1150                         return 1;
1151                 case PAM_SUCCESS:
1152                         return 0;
1153                 default:
1154                         break;
1155         }
1156         return -1;
1157 }
1158
1159 static char *_pam_delete(register char *xx)
1160 {
1161         _pam_overwrite(xx);
1162         _pam_drop(xx);
1163         return NULL;
1164 }
1165
1166 /*
1167  * obtain a password from the user
1168  */
1169
1170 static int _winbind_read_password(pam_handle_t * pamh,
1171                                   unsigned int ctrl,
1172                                   const char *comment,
1173                                   const char *prompt1,
1174                                   const char *prompt2,
1175                                   const char **pass)
1176 {
1177         int authtok_flag;
1178         int retval;
1179         const char *item;
1180         char *token;
1181
1182         _pam_log(pamh, ctrl, LOG_DEBUG, "getting password (0x%08x)", ctrl);
1183
1184         /*
1185          * make sure nothing inappropriate gets returned
1186          */
1187
1188         *pass = token = NULL;
1189
1190         /*
1191          * which authentication token are we getting?
1192          */
1193
1194         authtok_flag = on(WINBIND__OLD_PASSWORD, ctrl) ? PAM_OLDAUTHTOK : PAM_AUTHTOK;
1195
1196         /*
1197          * should we obtain the password from a PAM item ?
1198          */
1199
1200         if (on(WINBIND_TRY_FIRST_PASS_ARG, ctrl) || on(WINBIND_USE_FIRST_PASS_ARG, ctrl)) {
1201                 retval = _pam_get_item(pamh, authtok_flag, &item);
1202                 if (retval != PAM_SUCCESS) {
1203                         /* very strange. */
1204                         _pam_log(pamh, ctrl, LOG_ALERT, 
1205                                  "pam_get_item returned error to unix-read-password"
1206                             );
1207                         return retval;
1208                 } else if (item != NULL) {      /* we have a password! */
1209                         *pass = item;
1210                         item = NULL;
1211                         _pam_log(pamh, ctrl, LOG_DEBUG, 
1212                                  "pam_get_item returned a password");
1213                         return PAM_SUCCESS;
1214                 } else if (on(WINBIND_USE_FIRST_PASS_ARG, ctrl)) {
1215                         return PAM_AUTHTOK_RECOVER_ERR;         /* didn't work */
1216                 } else if (on(WINBIND_USE_AUTHTOK_ARG, ctrl)
1217                            && off(WINBIND__OLD_PASSWORD, ctrl)) {
1218                         return PAM_AUTHTOK_RECOVER_ERR;
1219                 }
1220         }
1221         /*
1222          * getting here implies we will have to get the password from the
1223          * user directly.
1224          */
1225
1226         {
1227                 struct pam_message msg[3], *pmsg[3];
1228                 struct pam_response *resp;
1229                 int i, replies;
1230
1231                 /* prepare to converse */
1232
1233                 if (comment != NULL && off(ctrl, WINBIND_SILENT)) {
1234                         pmsg[0] = &msg[0];
1235                         msg[0].msg_style = PAM_TEXT_INFO;
1236                         msg[0].msg = CONST_DISCARD(char *, comment);
1237                         i = 1;
1238                 } else {
1239                         i = 0;
1240                 }
1241
1242                 pmsg[i] = &msg[i];
1243                 msg[i].msg_style = PAM_PROMPT_ECHO_OFF;
1244                 msg[i++].msg = CONST_DISCARD(char *, prompt1);
1245                 replies = 1;
1246
1247                 if (prompt2 != NULL) {
1248                         pmsg[i] = &msg[i];
1249                         msg[i].msg_style = PAM_PROMPT_ECHO_OFF;
1250                         msg[i++].msg = CONST_DISCARD(char *, prompt2);
1251                         ++replies;
1252                 }
1253                 /* so call the conversation expecting i responses */
1254                 resp = NULL;
1255                 retval = converse(pamh, i, pmsg, &resp);
1256
1257                 if (resp != NULL) {
1258
1259                         /* interpret the response */
1260
1261                         if (retval == PAM_SUCCESS) {    /* a good conversation */
1262
1263                                 token = x_strdup(resp[i - replies].resp);
1264                                 if (token != NULL) {
1265                                         if (replies == 2) {
1266                                                 /* verify that password entered correctly */
1267                                                 if (!resp[i - 1].resp
1268                                                     || strcmp(token, resp[i - 1].resp)) {
1269                                                         _pam_delete(token);     /* mistyped */
1270                                                         retval = PAM_AUTHTOK_RECOVER_ERR;
1271                                                         _make_remark(pamh, ctrl, PAM_ERROR_MSG, MISTYPED_PASS);
1272                                                 }
1273                                         }
1274                                 } else {
1275                                         _pam_log(pamh, ctrl, LOG_NOTICE, "could not recover authentication token");
1276                                         retval = PAM_AUTHTOK_RECOVER_ERR;
1277                                 }
1278
1279                         }
1280                         /*
1281                          * tidy up the conversation (resp_retcode) is ignored
1282                          * -- what is it for anyway? AGM
1283                          */
1284
1285                         _pam_drop_reply(resp, i);
1286
1287                 } else {
1288                         retval = (retval == PAM_SUCCESS)
1289                             ? PAM_AUTHTOK_RECOVER_ERR : retval;
1290                 }
1291         }
1292
1293         if (retval != PAM_SUCCESS) {
1294                 _pam_log_debug(pamh, ctrl, LOG_DEBUG,
1295                                  "unable to obtain a password");
1296                 return retval;
1297         }
1298         /* 'token' is the entered password */
1299
1300         /* we store this password as an item */
1301         
1302         retval = pam_set_item(pamh, authtok_flag, token);
1303         _pam_delete(token);     /* clean it up */
1304         if (retval != PAM_SUCCESS || 
1305             (retval = _pam_get_item(pamh, authtok_flag, &item)) != PAM_SUCCESS) {
1306                 
1307                 _pam_log(pamh, ctrl, LOG_CRIT, "error manipulating password");
1308                 return retval;
1309                 
1310         }
1311
1312         *pass = item;
1313         item = NULL;            /* break link to password */
1314
1315         return PAM_SUCCESS;
1316 }
1317
1318 const char *get_conf_item_string(const pam_handle_t *pamh,
1319                                  int argc, 
1320                                  const char **argv, 
1321                                  int ctrl,
1322                                  dictionary *d,
1323                                  const char *item, 
1324                                  int config_flag)
1325 {
1326         int i = 0;
1327         const char *parm_opt = NULL;
1328         char *key = NULL;
1329
1330         if (!(ctrl & config_flag)) {
1331                 goto out;
1332         }
1333
1334         /* let the pam opt take precedence over the pam_winbind.conf option */
1335
1336         if (d != NULL) {
1337
1338                 if (!asprintf(&key, "global:%s", item)) {
1339                         goto out;
1340                 }
1341
1342                 parm_opt = iniparser_getstr(d, key);
1343                 SAFE_FREE(key);
1344         }
1345
1346         for ( i=0; i<argc; i++ ) {
1347
1348                 if ((strncmp(argv[i], item, strlen(item)) == 0)) {
1349                         char *p;
1350
1351                         if ( (p = strchr( argv[i], '=' )) == NULL) {
1352                                 _pam_log(pamh, ctrl, LOG_INFO, "no \"=\" delimiter for \"%s\" found\n", item);
1353                                 goto out;
1354                         }
1355                         _pam_log_debug(pamh, ctrl, LOG_INFO, "PAM config: %s '%s'\n", item, p+1);
1356                         return p + 1;
1357                 }
1358         }
1359
1360         if (d != NULL) {
1361                 _pam_log_debug(pamh, ctrl, LOG_INFO, "CONFIG file: %s '%s'\n", item, parm_opt);
1362         }
1363 out:
1364         return parm_opt;
1365 }
1366
1367 const char *get_krb5_cc_type_from_config(const pam_handle_t *pamh, int argc, const char **argv, int ctrl, dictionary *d)
1368 {
1369         return get_conf_item_string(pamh, argc, argv, ctrl, d, "krb5_ccache_type", WINBIND_KRB5_CCACHE_TYPE);
1370 }
1371
1372 const char *get_member_from_config(const pam_handle_t *pamh, int argc, const char **argv, int ctrl, dictionary *d)
1373 {
1374         const char *ret = NULL;
1375         ret = get_conf_item_string(pamh, argc, argv, ctrl, d, "require_membership_of", WINBIND_REQUIRED_MEMBERSHIP);
1376         if (ret) {
1377                 return ret;
1378         }
1379         return get_conf_item_string(pamh, argc, argv, ctrl, d, "require-membership-of", WINBIND_REQUIRED_MEMBERSHIP);
1380 }
1381
1382 PAM_EXTERN
1383 int pam_sm_authenticate(pam_handle_t *pamh, int flags,
1384                         int argc, const char **argv)
1385 {
1386         const char *username;
1387         const char *password;
1388         const char *member = NULL;
1389         const char *cctype = NULL;
1390         int retval = PAM_AUTH_ERR;
1391         dictionary *d = NULL;
1392         char *username_ret = NULL;
1393         char *new_authtok_required = NULL;
1394
1395         /* parse arguments */
1396         int ctrl = _pam_parse(pamh, flags, argc, argv, &d);
1397         if (ctrl == -1) {
1398                 retval = PAM_SYSTEM_ERR;
1399                 goto out;
1400         }
1401
1402         _PAM_LOG_FUNCTION_ENTER("pam_sm_authenticate", pamh, ctrl, flags);
1403
1404         /* Get the username */
1405         retval = pam_get_user(pamh, &username, NULL);
1406         if ((retval != PAM_SUCCESS) || (!username)) {
1407                 _pam_log_debug(pamh, ctrl, LOG_DEBUG, "can not get the username");
1408                 retval = PAM_SERVICE_ERR;
1409                 goto out;
1410         }
1411
1412         retval = _winbind_read_password(pamh, ctrl, NULL, 
1413                                         "Password: ", NULL,
1414                                         &password);
1415
1416         if (retval != PAM_SUCCESS) {
1417                 _pam_log(pamh, ctrl, LOG_ERR, "Could not retrieve user's password");
1418                 retval = PAM_AUTHTOK_ERR;
1419                 goto out;
1420         }
1421
1422         /* Let's not give too much away in the log file */
1423
1424 #ifdef DEBUG_PASSWORD
1425         _pam_log_debug(pamh, ctrl, LOG_INFO, "Verify user '%s' with password '%s'", 
1426                        username, password);
1427 #else
1428         _pam_log_debug(pamh, ctrl, LOG_INFO, "Verify user '%s'", username);
1429 #endif
1430
1431         member = get_member_from_config(pamh, argc, argv, ctrl, d);
1432
1433         cctype = get_krb5_cc_type_from_config(pamh, argc, argv, ctrl, d);
1434
1435         /* Now use the username to look up password */
1436         retval = winbind_auth_request(pamh, ctrl, username, password, member,
1437                                       cctype, NULL, NULL, &username_ret);
1438
1439         if (retval == PAM_NEW_AUTHTOK_REQD ||
1440             retval == PAM_AUTHTOK_EXPIRED) {
1441
1442                 if (!asprintf(&new_authtok_required, "%d", retval)) {
1443                         retval = PAM_BUF_ERR;
1444                         goto out;
1445                 }
1446
1447                 pam_set_data(pamh, PAM_WINBIND_NEW_AUTHTOK_REQD, new_authtok_required, _pam_winbind_cleanup_func);
1448
1449                 retval = PAM_SUCCESS;
1450                 goto out;
1451         }
1452
1453 out:
1454         if (username_ret) {
1455                 pam_set_item (pamh, PAM_USER, username_ret);
1456                 _pam_log_debug(pamh, ctrl, LOG_INFO, "Returned user was '%s'", username_ret);
1457                 free(username_ret);
1458         }
1459
1460         if (d) {
1461                 iniparser_freedict(d);
1462         }
1463
1464         if (!new_authtok_required) {
1465                 pam_set_data(pamh, PAM_WINBIND_NEW_AUTHTOK_REQD, NULL, NULL);
1466         }
1467
1468         _PAM_LOG_FUNCTION_LEAVE("pam_sm_authenticate", pamh, ctrl, retval);
1469
1470         return retval;
1471 }
1472
1473 PAM_EXTERN
1474 int pam_sm_setcred(pam_handle_t *pamh, int flags,
1475                    int argc, const char **argv)
1476 {
1477         int ret = PAM_SYSTEM_ERR;
1478         dictionary *d = NULL;
1479
1480         /* parse arguments */
1481         int ctrl = _pam_parse(pamh, flags, argc, argv, &d);
1482         if (ctrl == -1) {
1483                 ret = PAM_SYSTEM_ERR;
1484                 goto out;
1485         }
1486
1487         _PAM_LOG_FUNCTION_ENTER("pam_sm_setcred", pamh, ctrl, flags);
1488
1489         switch (flags & ~PAM_SILENT) {
1490
1491                 case PAM_DELETE_CRED:
1492                         ret = pam_sm_close_session(pamh, flags, argc, argv);
1493                         break;
1494                 case PAM_REFRESH_CRED:
1495                         _pam_log_debug(pamh, ctrl, LOG_WARNING, "PAM_REFRESH_CRED not implemented");
1496                         ret = PAM_SUCCESS;
1497                         break;
1498                 case PAM_REINITIALIZE_CRED:
1499                         _pam_log_debug(pamh, ctrl, LOG_WARNING, "PAM_REINITIALIZE_CRED not implemented");
1500                         ret = PAM_SUCCESS;
1501                         break;
1502                 case PAM_ESTABLISH_CRED:
1503                         _pam_log_debug(pamh, ctrl, LOG_WARNING, "PAM_ESTABLISH_CRED not implemented");
1504                         ret = PAM_SUCCESS;
1505                         break;
1506                 default:
1507                         ret = PAM_SYSTEM_ERR;
1508                         break;
1509         }
1510
1511  out:
1512         if (d) {
1513                 iniparser_freedict(d);
1514         }
1515
1516         _PAM_LOG_FUNCTION_LEAVE("pam_sm_setcred", pamh, ctrl, ret);
1517         
1518         return ret;
1519 }
1520
1521 /*
1522  * Account management. We want to verify that the account exists 
1523  * before returning PAM_SUCCESS
1524  */
1525 PAM_EXTERN
1526 int pam_sm_acct_mgmt(pam_handle_t *pamh, int flags,
1527                    int argc, const char **argv)
1528 {
1529         const char *username;
1530         int ret = PAM_USER_UNKNOWN;
1531         void *tmp = NULL;
1532         dictionary *d = NULL;
1533
1534         /* parse arguments */
1535         int ctrl = _pam_parse(pamh, flags, argc, argv, &d);
1536         if (ctrl == -1) {
1537                 return PAM_SYSTEM_ERR;
1538         }
1539
1540         _PAM_LOG_FUNCTION_ENTER("pam_sm_acct_mgmt", pamh, ctrl, flags);
1541
1542
1543         /* Get the username */
1544         ret = pam_get_user(pamh, &username, NULL);
1545         if ((ret != PAM_SUCCESS) || (!username)) {
1546                 _pam_log_debug(pamh, ctrl, LOG_DEBUG,"can not get the username");
1547                 ret = PAM_SERVICE_ERR;
1548                 goto out;
1549         }
1550
1551         /* Verify the username */
1552         ret = valid_user(pamh, ctrl, username);
1553         switch (ret) {
1554         case -1:
1555                 /* some sort of system error. The log was already printed */
1556                 ret = PAM_SERVICE_ERR;
1557                 goto out;
1558         case 1:
1559                 /* the user does not exist */
1560                 _pam_log_debug(pamh, ctrl, LOG_NOTICE, "user '%s' not found", username);
1561                 if (ctrl & WINBIND_UNKNOWN_OK_ARG) {
1562                         ret = PAM_IGNORE;
1563                         goto out;
1564                 }
1565                 ret = PAM_USER_UNKNOWN;
1566                 goto out;
1567         case 0:
1568                 pam_get_data( pamh, PAM_WINBIND_NEW_AUTHTOK_REQD, (const void **)&tmp);
1569                 if (tmp != NULL) {
1570                         ret = atoi((const char *)tmp);
1571                         switch (ret) {
1572                         case PAM_AUTHTOK_EXPIRED:
1573                                 /* fall through, since new token is required in this case */
1574                         case PAM_NEW_AUTHTOK_REQD:
1575                                 _pam_log(pamh, ctrl, LOG_WARNING, "pam_sm_acct_mgmt success but %s is set", 
1576                                          PAM_WINBIND_NEW_AUTHTOK_REQD);
1577                                 _pam_log(pamh, ctrl, LOG_NOTICE, "user '%s' needs new password", username);
1578                                 /* PAM_AUTHTOKEN_REQD does not exist, but is documented in the manpage */
1579                                 ret = PAM_NEW_AUTHTOK_REQD;
1580                                 goto out;
1581                         default:
1582                                 _pam_log(pamh, ctrl, LOG_WARNING, "pam_sm_acct_mgmt success");
1583                                 _pam_log(pamh, ctrl, LOG_NOTICE, "user '%s' granted access", username);
1584                                 ret = PAM_SUCCESS;
1585                                 goto out;
1586                         }
1587                 }
1588
1589                 /* Otherwise, the authentication looked good */
1590                 _pam_log(pamh, ctrl, LOG_NOTICE, "user '%s' granted access", username);
1591                 ret = PAM_SUCCESS;
1592                 goto out;
1593         default:
1594                 /* we don't know anything about this return value */
1595                 _pam_log(pamh, ctrl, LOG_ERR, "internal module error (ret = %d, user = '%s')", 
1596                          ret, username);
1597                 ret = PAM_SERVICE_ERR;
1598                 goto out;
1599         }
1600
1601         /* should not be reached */
1602         ret = PAM_IGNORE;
1603
1604  out:
1605
1606         if (d) {
1607                 iniparser_freedict(d);
1608         }
1609
1610         _PAM_LOG_FUNCTION_LEAVE("pam_sm_acct_mgmt", pamh, ctrl, ret);
1611         
1612         return ret;
1613 }
1614
1615 PAM_EXTERN
1616 int pam_sm_open_session(pam_handle_t *pamh, int flags,
1617                         int argc, const char **argv)
1618 {
1619         int ret = PAM_SYSTEM_ERR;
1620         dictionary *d = NULL;
1621
1622         /* parse arguments */
1623         int ctrl = _pam_parse(pamh, flags, argc, argv, &d);
1624         if (ctrl == -1) {
1625                 ret = PAM_SYSTEM_ERR;
1626                 goto out;
1627         }
1628
1629         _PAM_LOG_FUNCTION_ENTER("pam_sm_open_session", pamh, ctrl, flags);
1630
1631         ret = PAM_SUCCESS;
1632
1633  out:
1634         if (d) {
1635                 iniparser_freedict(d);
1636         }
1637
1638         _PAM_LOG_FUNCTION_LEAVE("pam_sm_open_session", pamh, ctrl, ret);
1639         
1640         return ret;
1641 }
1642
1643 PAM_EXTERN
1644 int pam_sm_close_session(pam_handle_t *pamh, int flags,
1645                          int argc, const char **argv)
1646 {
1647         dictionary *d = NULL;
1648         int retval = PAM_SUCCESS;
1649
1650         /* parse arguments */
1651         int ctrl = _pam_parse(pamh, flags, argc, argv, &d);
1652         if (ctrl == -1) {
1653                 retval = PAM_SYSTEM_ERR;
1654                 goto out;
1655         }
1656
1657         _PAM_LOG_FUNCTION_ENTER("pam_sm_close_session", pamh, ctrl, flags);
1658
1659         if (!(flags & PAM_DELETE_CRED)) {
1660                 retval = PAM_SUCCESS;
1661                 goto out;
1662         }
1663
1664         if (ctrl & WINBIND_KRB5_AUTH) {
1665
1666                 /* destroy the ccache here */
1667                 struct winbindd_request request;
1668                 struct winbindd_response response;
1669                 const char *user;
1670                 const char *ccname = NULL;
1671                 struct passwd *pwd = NULL;
1672
1673                 ZERO_STRUCT(request);
1674                 ZERO_STRUCT(response);
1675
1676                 retval = pam_get_user(pamh, &user, "Username: ");
1677                 if (retval) {
1678                         _pam_log(pamh, ctrl, LOG_ERR, "could not identify user");
1679                         goto out;
1680                 }
1681
1682                 if (user == NULL) {
1683                         _pam_log(pamh, ctrl, LOG_ERR, "username was NULL!");
1684                         retval = PAM_USER_UNKNOWN;
1685                         goto out;
1686                 }
1687
1688                 _pam_log_debug(pamh, ctrl, LOG_DEBUG, "username [%s] obtained", user);
1689
1690                 ccname = pam_getenv(pamh, "KRB5CCNAME");
1691                 if (ccname == NULL) {
1692                         _pam_log_debug(pamh, ctrl, LOG_DEBUG, "user has no KRB5CCNAME environment");
1693                 }
1694
1695                 strncpy(request.data.logoff.user, user,
1696                         sizeof(request.data.logoff.user) - 1);
1697
1698                 if (ccname) {
1699                         strncpy(request.data.logoff.krb5ccname, ccname,
1700                                 sizeof(request.data.logoff.krb5ccname) - 1);
1701                 }
1702
1703                 pwd = getpwnam(user);
1704                 if (pwd == NULL) {
1705                         retval = PAM_USER_UNKNOWN;
1706                         goto out;
1707                 }
1708                 request.data.logoff.uid = pwd->pw_uid;
1709
1710                 request.flags = WBFLAG_PAM_KRB5 | WBFLAG_PAM_CONTACT_TRUSTDOM;
1711
1712                 retval = pam_winbind_request_log(pamh, ctrl, WINBINDD_PAM_LOGOFF, &request, &response, user);
1713         }
1714
1715 out:
1716         if (d) {
1717                 iniparser_freedict(d);
1718         }
1719
1720         _PAM_LOG_FUNCTION_LEAVE("pam_sm_close_session", pamh, ctrl, retval);
1721         
1722         return retval;
1723 }
1724
1725
1726
1727 PAM_EXTERN 
1728 int pam_sm_chauthtok(pam_handle_t * pamh, int flags,
1729                      int argc, const char **argv)
1730 {
1731         unsigned int lctrl;
1732         int ret;
1733         unsigned int ctrl;
1734
1735         /* <DO NOT free() THESE> */
1736         const char *user;
1737         char *pass_old, *pass_new;
1738         /* </DO NOT free() THESE> */
1739
1740         char *Announce;
1741         
1742         int retry = 0;
1743         dictionary *d = NULL;
1744
1745         ctrl = _pam_parse(pamh, flags, argc, argv, &d);
1746         if (ctrl == -1) {
1747                 ret = PAM_SYSTEM_ERR;
1748                 goto out;
1749         }
1750
1751         _PAM_LOG_FUNCTION_ENTER("pam_sm_chauthtok", pamh, ctrl, flags);
1752
1753         /* clearing offline bit for the auth in the password change */
1754         ctrl &= ~WINBIND_CACHED_LOGIN;
1755
1756         /*
1757          * First get the name of a user
1758          */
1759         ret = pam_get_user(pamh, &user, "Username: ");
1760         if (ret) {
1761                 _pam_log(pamh, ctrl, LOG_ERR,
1762                          "password - could not identify user");
1763                 goto out;
1764         }
1765
1766         if (user == NULL) {
1767                 _pam_log(pamh, ctrl, LOG_ERR, "username was NULL!");
1768                 ret = PAM_USER_UNKNOWN;
1769                 goto out;
1770         }
1771
1772         _pam_log_debug(pamh, ctrl, LOG_DEBUG, "username [%s] obtained", user);
1773
1774         /* check if this is really a user in winbindd, not only in NSS */
1775         ret = valid_user(pamh, ctrl, user);
1776         switch (ret) {
1777                 case 1:
1778                         ret = PAM_USER_UNKNOWN;
1779                         goto out;
1780                 case -1:
1781                         ret = PAM_SYSTEM_ERR;
1782                         goto out;
1783                 default:
1784                         break;
1785         }
1786                 
1787         /*
1788          * obtain and verify the current password (OLDAUTHTOK) for
1789          * the user.
1790          */
1791
1792         if (flags & PAM_PRELIM_CHECK) {
1793                 struct winbindd_response response;
1794                 time_t pwdlastset_prelim = 0;
1795                 
1796                 /* instruct user what is happening */
1797 #define greeting "Changing password for "
1798                 Announce = (char *) malloc(sizeof(greeting) + strlen(user));
1799                 if (Announce == NULL) {
1800                         _pam_log(pamh, ctrl, LOG_CRIT, "password - out of memory");
1801                         ret = PAM_BUF_ERR;
1802                         goto out;
1803                 }
1804                 (void) strcpy(Announce, greeting);
1805                 (void) strcpy(Announce + sizeof(greeting) - 1, user);
1806 #undef greeting
1807                 
1808                 lctrl = ctrl | WINBIND__OLD_PASSWORD;
1809                 ret = _winbind_read_password(pamh, lctrl,
1810                                                 Announce,
1811                                                 "(current) NT password: ",
1812                                                 NULL,
1813                                                 (const char **) &pass_old);
1814                 if (ret != PAM_SUCCESS) {
1815                         _pam_log(pamh, ctrl, LOG_NOTICE, "password - (old) token not obtained");
1816                         goto out;
1817                 }
1818
1819                 /* We don't need krb5 env set for password change test. */
1820                 ctrl &= ~WINBIND_KRB5_AUTH;
1821
1822                 /* verify that this is the password for this user */
1823                 
1824                 ret = winbind_auth_request(pamh, ctrl, user, pass_old,
1825                                         NULL, NULL, &response, &pwdlastset_prelim, NULL);
1826
1827                 if (ret != PAM_ACCT_EXPIRED && 
1828                     ret != PAM_AUTHTOK_EXPIRED &&
1829                     ret != PAM_NEW_AUTHTOK_REQD &&
1830                     ret != PAM_SUCCESS) {
1831                         pass_old = NULL;
1832                         if (d) {
1833                                 iniparser_freedict(d);
1834                         }
1835                         /* Deal with offline errors. */
1836                         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl,
1837                                                 response,
1838                                                 "NT_STATUS_NO_LOGON_SERVERS");
1839                         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl,
1840                                                 response,
1841                                                 "NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND");
1842                         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl,
1843                                                 response,
1844                                                 "NT_STATUS_ACCESS_DENIED");
1845                         return ret;
1846                 }
1847                 
1848                 pam_set_data(pamh, PAM_WINBIND_PWD_LAST_SET, (void *)pwdlastset_prelim, NULL);
1849
1850                 ret = pam_set_item(pamh, PAM_OLDAUTHTOK, (const void *) pass_old);
1851                 pass_old = NULL;
1852                 if (ret != PAM_SUCCESS) {
1853                         _pam_log(pamh, ctrl, LOG_CRIT, "failed to set PAM_OLDAUTHTOK");
1854                 }
1855         } else if (flags & PAM_UPDATE_AUTHTOK) {
1856         
1857                 time_t pwdlastset_update = 0;
1858                 
1859                 /*
1860                  * obtain the proposed password
1861                  */
1862                 
1863                 /*
1864                  * get the old token back. 
1865                  */
1866                 
1867                 ret = _pam_get_item(pamh, PAM_OLDAUTHTOK, &pass_old);
1868                 
1869                 if (ret != PAM_SUCCESS) {
1870                         _pam_log(pamh, ctrl, LOG_NOTICE, "user not authenticated");
1871                         goto out;
1872                 }
1873                 
1874                 lctrl = ctrl & ~WINBIND_TRY_FIRST_PASS_ARG;
1875                 
1876                 if (on(WINBIND_USE_AUTHTOK_ARG, lctrl)) {
1877                         lctrl |= WINBIND_USE_FIRST_PASS_ARG;
1878                 }
1879                 retry = 0;
1880                 ret = PAM_AUTHTOK_ERR;
1881                 while ((ret != PAM_SUCCESS) && (retry++ < MAX_PASSWD_TRIES)) {
1882                         /*
1883                          * use_authtok is to force the use of a previously entered
1884                          * password -- needed for pluggable password strength checking
1885                          */
1886                         
1887                         ret = _winbind_read_password(pamh, lctrl,
1888                                                         NULL,
1889                                                         "Enter new NT password: ",
1890                                                         "Retype new NT password: ",
1891                                                         (const char **) &pass_new);
1892                         
1893                         if (ret != PAM_SUCCESS) {
1894                                 _pam_log_debug(pamh, ctrl, LOG_ALERT
1895                                          ,"password - new password not obtained");
1896                                 pass_old = NULL;/* tidy up */
1897                                 goto out;
1898                         }
1899
1900                         /*
1901                          * At this point we know who the user is and what they
1902                          * propose as their new password. Verify that the new
1903                          * password is acceptable.
1904                          */
1905                         
1906                         if (pass_new[0] == '\0') {/* "\0" password = NULL */
1907                                 pass_new = NULL;
1908                         }
1909                 }
1910                 
1911                 /*
1912                  * By reaching here we have approved the passwords and must now
1913                  * rebuild the password database file.
1914                  */
1915                 _pam_get_data( pamh, PAM_WINBIND_PWD_LAST_SET,
1916                                &pwdlastset_update);
1917
1918                 ret = winbind_chauthtok_request(pamh, ctrl, user, pass_old, pass_new, pwdlastset_update);
1919                 if (ret) {
1920                         _pam_overwrite(pass_new);
1921                         _pam_overwrite(pass_old);
1922                         pass_old = pass_new = NULL;
1923                         goto out;
1924                 }
1925
1926                 /* just in case we need krb5 creds after a password change over msrpc */
1927
1928                 if (ctrl & WINBIND_KRB5_AUTH) {
1929                         struct winbindd_response response;
1930
1931                         const char *member = get_member_from_config(pamh, argc, argv, ctrl, d);
1932                         const char *cctype = get_krb5_cc_type_from_config(pamh, argc, argv, ctrl, d);
1933
1934                         ret = winbind_auth_request(pamh, ctrl, user, pass_new,
1935                                                         member, cctype, &response, NULL, NULL);
1936                         _pam_overwrite(pass_new);
1937                         _pam_overwrite(pass_old);
1938                         pass_old = pass_new = NULL;
1939                         if (d) {
1940                                 iniparser_freedict(d);
1941                         }
1942                         /* Deal with offline errors. */
1943                         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl,
1944                                                 response,
1945                                                 "NT_STATUS_NO_LOGON_SERVERS");
1946                         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl,
1947                                                 response,
1948                                                 "NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND");
1949                         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, ctrl,
1950                                                 response,
1951                                                 "NT_STATUS_ACCESS_DENIED");
1952                         return ret;
1953                 }
1954         } else {
1955                 ret = PAM_SERVICE_ERR;
1956         }
1957
1958 out:
1959         if (d) {
1960                 iniparser_freedict(d);
1961         }
1962
1963         _PAM_LOG_FUNCTION_LEAVE("pam_sm_chauthtok", pamh, ctrl, ret);
1964         
1965         return ret;
1966 }
1967
1968 #ifdef PAM_STATIC
1969
1970 /* static module data */
1971
1972 struct pam_module _pam_winbind_modstruct = {
1973         MODULE_NAME,
1974         pam_sm_authenticate,
1975         pam_sm_setcred,
1976         pam_sm_acct_mgmt,
1977         pam_sm_open_session,
1978         pam_sm_close_session,
1979         pam_sm_chauthtok
1980 };
1981
1982 #endif
1983
1984 /*
1985  * Copyright (c) Andrew Tridgell  <tridge@samba.org>   2000
1986  * Copyright (c) Tim Potter       <tpot@samba.org>     2000
1987  * Copyright (c) Andrew Bartlettt <abartlet@samba.org> 2002
1988  * Copyright (c) Guenther Deschner <gd@samba.org>      2005-2007
1989  * Copyright (c) Jan Rêkorajski 1999.
1990  * Copyright (c) Andrew G. Morgan 1996-8.
1991  * Copyright (c) Alex O. Yuriev, 1996.
1992  * Copyright (c) Cristian Gafton 1996.
1993  * Copyright (C) Elliot Lee <sopwith@redhat.com> 1996, Red Hat Software. 
1994  *
1995  * Redistribution and use in source and binary forms, with or without
1996  * modification, are permitted provided that the following conditions
1997  * are met:
1998  * 1. Redistributions of source code must retain the above copyright
1999  *    notice, and the entire permission notice in its entirety,
2000  *    including the disclaimer of warranties.
2001  * 2. Redistributions in binary form must reproduce the above copyright
2002  *    notice, this list of conditions and the following disclaimer in the
2003  *    documentation and/or other materials provided with the distribution.
2004  * 3. The name of the author may not be used to endorse or promote
2005  *    products derived from this software without specific prior
2006  *    written permission.
2007  *
2008  * ALTERNATIVELY, this product may be distributed under the terms of
2009  * the GNU Public License, in which case the provisions of the GPL are
2010  * required INSTEAD OF the above restrictions.  (This clause is
2011  * necessary due to a potential bad interaction between the GPL and
2012  * the restrictions contained in a BSD-style copyright.)
2013  *
2014  * THIS SOFTWARE IS PROVIDED `AS IS'' AND ANY EXPRESS OR IMPLIED
2015  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
2016  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
2017  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
2018  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
2019  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2020  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2021  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
2022  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
2023  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
2024  * OF THE POSSIBILITY OF SUCH DAMAGE.
2025  */