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