r20239: Parse the configfile for pam_sm_setcred as well
[kai/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-2006
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 /* data tokens */
16
17 #define MAX_PASSWD_TRIES        3
18
19 /*
20  * Work around the pam API that has functions with void ** as parameters.
21  * These lead to strict aliasing warnings with gcc.
22  */
23 static int _pam_get_item(const pam_handle_t *pamh, int item_type,
24                          const void *_item)
25 {
26         const void **item = (const void **)_item;
27         return pam_get_item(pamh, item_type, item);
28 }
29 static int _pam_get_data(const pam_handle_t *pamh,
30                          const char *module_data_name, const void *_data)
31 {
32         const void **data = (const void **)_data;
33         return pam_get_data(pamh, module_data_name, data);
34 }
35
36 /* some syslogging */
37
38 static void _pam_log_int(const pam_handle_t *pamh, int err, const char *format, va_list args)
39 {
40
41 #ifdef HAVE_PAM_VSYSLOG
42         pam_vsyslog(pamh, err, format, args);
43 #else
44         {
45
46         char *format2 = NULL;
47         const char *service;
48
49         _pam_get_item(pamh, PAM_SERVICE, &service);
50
51         format2 = malloc(strlen(MODULE_NAME)+strlen(format)+strlen(service)+5);
52         if (format2 == NULL) {
53                 /* what else todo ? */
54                 vsyslog(err, format, args);
55                 return;
56         }
57
58         sprintf(format2, "%s(%s): %s", MODULE_NAME, service, format);
59         vsyslog(err, format2, args);
60         SAFE_FREE(format2);
61         }
62 #endif
63 }
64
65 static void _pam_log(const pam_handle_t *pamh, int ctrl, int err, const char *format, ...)
66 {
67         va_list args;
68
69         if (ctrl & WINBIND_SILENT) {
70                 return;
71         }
72
73         va_start(args, format);
74         _pam_log_int(pamh, err, format, args);
75         va_end(args);
76 }
77
78 static void _pam_log_debug(const pam_handle_t *pamh, int ctrl, int err, const char *format, ...)
79 {
80         va_list args;
81
82         if (ctrl & WINBIND_SILENT) {
83                 return;
84         }
85
86         if (!(ctrl & WINBIND_DEBUG_ARG)) {
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 int _pam_parse(const pam_handle_t *pamh, int flags, int argc, const char **argv, dictionary **d)
96 {
97         int ctrl = 0;
98         const char *config_file = NULL;
99         int i;
100         const char **v;
101
102         if (flags & PAM_SILENT) {
103                 ctrl |= WINBIND_SILENT;
104         }
105
106         if (d == NULL) {
107                 goto config_from_pam;
108         }
109
110         for (i=argc,v=argv; i-- > 0; ++v) {
111                 if (!strncasecmp(*v, "config", strlen("config"))) {
112                         ctrl |= WINBIND_CONFIG_FILE;
113                         config_file = v[i];
114                         break;
115                 }
116         }
117
118         if (config_file == NULL) {
119                 config_file = PAM_WINBIND_CONFIG_FILE;
120         }
121
122         *d = iniparser_load(config_file);
123         if (*d == NULL) {
124                 goto config_from_pam;
125         }
126
127         if (iniparser_getboolean(*d, "global:debug", False)) {
128                 ctrl |= WINBIND_DEBUG_ARG;
129         }
130
131         if (iniparser_getboolean(*d, "global:cached_login", False)) {
132                 ctrl |= WINBIND_CACHED_LOGIN;
133         }
134
135         if (iniparser_getboolean(*d, "global:krb5_auth", False)) {
136                 ctrl |= WINBIND_KRB5_AUTH;
137         }
138
139         if (iniparser_getboolean(*d, "global:silent", False)) {
140                 ctrl |= WINBIND_SILENT;
141         }
142
143         if (iniparser_getstr(*d, "global:krb5_ccache_type") != NULL) {
144                 ctrl |= WINBIND_KRB5_CCACHE_TYPE;
145         }
146         
147         if ((iniparser_getstr(*d, "global:require-membership-of") != NULL) ||
148             (iniparser_getstr(*d, "global:require_membership_of") != NULL)) {
149                 ctrl |= WINBIND_REQUIRED_MEMBERSHIP;
150         }
151
152 config_from_pam:
153         /* step through arguments */
154         for (i=argc,v=argv; i-- > 0; ++v) {
155
156                 /* generic options */
157                 if (!strcmp(*v,"debug"))
158                         ctrl |= WINBIND_DEBUG_ARG;
159                 else if (!strcasecmp(*v, "use_authtok"))
160                         ctrl |= WINBIND_USE_AUTHTOK_ARG;
161                 else if (!strcasecmp(*v, "use_first_pass"))
162                         ctrl |= WINBIND_USE_FIRST_PASS_ARG;
163                 else if (!strcasecmp(*v, "try_first_pass"))
164                         ctrl |= WINBIND_TRY_FIRST_PASS_ARG;
165                 else if (!strcasecmp(*v, "unknown_ok"))
166                         ctrl |= WINBIND_UNKNOWN_OK_ARG;
167                 else if (!strncasecmp(*v, "require_membership_of", strlen("require_membership_of")))
168                         ctrl |= WINBIND_REQUIRED_MEMBERSHIP;
169                 else if (!strncasecmp(*v, "require-membership-of", strlen("require-membership-of")))
170                         ctrl |= WINBIND_REQUIRED_MEMBERSHIP;
171                 else if (!strcasecmp(*v, "krb5_auth"))
172                         ctrl |= WINBIND_KRB5_AUTH;
173                 else if (!strncasecmp(*v, "krb5_ccache_type", strlen("krb5_ccache_type")))
174                         ctrl |= WINBIND_KRB5_CCACHE_TYPE;
175                 else if (!strcasecmp(*v, "cached_login"))
176                         ctrl |= WINBIND_CACHED_LOGIN;
177                 else {
178                         _pam_log(pamh, ctrl, LOG_ERR, "pam_parse: unknown option; %s", *v);
179                 }
180
181         }
182         return ctrl;
183 };
184
185 static void _pam_winbind_cleanup_func(pam_handle_t *pamh, void *data, int error_status)
186 {
187         SAFE_FREE(data);
188 }
189
190
191 static const struct ntstatus_errors {
192         const char *ntstatus_string;
193         const char *error_string;
194 } ntstatus_errors[] = {
195         {"NT_STATUS_OK", "Success"},
196         {"NT_STATUS_BACKUP_CONTROLLER", "No primary Domain Controler available"},
197         {"NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND", "No domain controllers found"},
198         {"NT_STATUS_NO_LOGON_SERVERS", "No logon servers"},
199         {"NT_STATUS_PWD_TOO_SHORT", "Password too short"},
200         {"NT_STATUS_PWD_TOO_RECENT", "The password of this user is too recent to change"},
201         {"NT_STATUS_PWD_HISTORY_CONFLICT", "Password is already in password history"},
202         {"NT_STATUS_PASSWORD_EXPIRED", "Your password has expired"},
203         {"NT_STATUS_PASSWORD_MUST_CHANGE", "You need to change your password now"},
204         {"NT_STATUS_INVALID_WORKSTATION", "You are not allowed to logon from this workstation"},
205         {"NT_STATUS_INVALID_LOGON_HOURS", "You are not allowed to logon at this time"},
206         {"NT_STATUS_ACCOUNT_EXPIRED", "Your account has expired. Please contact your System administrator"}, /* SCNR */
207         {"NT_STATUS_ACCOUNT_DISABLED", "Your account is disabled. Please contact your System administrator"}, /* SCNR */
208         {"NT_STATUS_ACCOUNT_LOCKED_OUT", "Your account has been locked. Please contact your System administrator"}, /* SCNR */
209         {"NT_STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT", "Invalid Trust Account"},
210         {"NT_STATUS_NOLOGON_SERVER_TRUST_ACCOUNT", "Invalid Trust Account"},
211         {"NT_STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT", "Invalid Trust Account"},
212         {"NT_STATUS_ACCESS_DENIED", "Access is denied"},
213         {NULL, NULL}
214 };
215
216 const char *_get_ntstatus_error_string(const char *nt_status_string) 
217 {
218         int i;
219         for (i=0; ntstatus_errors[i].ntstatus_string != NULL; i++) {
220                 if (!strcasecmp(ntstatus_errors[i].ntstatus_string, nt_status_string)) {
221                         return ntstatus_errors[i].error_string;
222                 }
223         }
224         return NULL;
225 }
226
227 /* --- authentication management functions --- */
228
229 /* Attempt a conversation */
230
231 static int converse(pam_handle_t *pamh, int nargs,
232                     struct pam_message **message,
233                     struct pam_response **response)
234 {
235         int retval;
236         struct pam_conv *conv;
237
238         retval = _pam_get_item(pamh, PAM_CONV, &conv );
239         if (retval == PAM_SUCCESS) {
240                 retval = conv->conv(nargs, (const struct pam_message **)message,
241                                     response, conv->appdata_ptr);
242         }
243         
244         return retval; /* propagate error status */
245 }
246
247
248 static int _make_remark(pam_handle_t * pamh, int type, const char *text)
249 {
250         int retval = PAM_SUCCESS;
251
252         struct pam_message *pmsg[1], msg[1];
253         struct pam_response *resp;
254         
255         pmsg[0] = &msg[0];
256         msg[0].msg = CONST_DISCARD(char *, text);
257         msg[0].msg_style = type;
258         
259         resp = NULL;
260         retval = converse(pamh, 1, pmsg, &resp);
261         
262         if (resp) {
263                 _pam_drop_reply(resp, 1);
264         }
265         return retval;
266 }
267
268 static int _make_remark_format(pam_handle_t * pamh, int type, const char *format, ...)
269 {
270         va_list args;
271         char *var;
272         int ret;
273
274         va_start(args, format);
275         vasprintf(&var, format, args);
276         va_end(args);
277
278         ret = _make_remark(pamh, type, var);
279         SAFE_FREE(var);
280         return ret;
281 }
282
283 static int pam_winbind_request(pam_handle_t * pamh, int ctrl,
284                                enum winbindd_cmd req_type,
285                                struct winbindd_request *request,
286                                struct winbindd_response *response)
287 {
288         /* Fill in request and send down pipe */
289         init_request(request, req_type);
290         
291         if (write_sock(request, sizeof(*request), 0) == -1) {
292                 _pam_log(pamh, ctrl, LOG_ERR, "pam_winbind_request: write to socket failed!");
293                 close_sock();
294                 return PAM_SERVICE_ERR;
295         }
296         
297         /* Wait for reply */
298         if (read_reply(response) == -1) {
299                 _pam_log(pamh, ctrl, LOG_ERR, "pam_winbind_request: read from socket failed!");
300                 close_sock();
301                 return PAM_SERVICE_ERR;
302         }
303
304         /* We are done with the socket - close it and avoid mischeif */
305         close_sock();
306
307         /* Copy reply data from socket */
308         if (response->result != WINBINDD_OK) {
309                 if (response->data.auth.pam_error != PAM_SUCCESS) {
310                         _pam_log(pamh, ctrl, LOG_ERR, "request failed: %s, PAM error was %s (%d), NT error was %s", 
311                                  response->data.auth.error_string,
312                                  pam_strerror(pamh, response->data.auth.pam_error),
313                                  response->data.auth.pam_error,
314                                  response->data.auth.nt_status_string);
315                         return response->data.auth.pam_error;
316                 } else {
317                         _pam_log(pamh, ctrl, LOG_ERR, "request failed, but PAM error 0!");
318                         return PAM_SERVICE_ERR;
319                 }
320         }
321
322         return PAM_SUCCESS;
323 }
324
325 static int pam_winbind_request_log(pam_handle_t * pamh,
326                                    int ctrl,
327                                    enum winbindd_cmd req_type,
328                                    struct winbindd_request *request,
329                                    struct winbindd_response *response,
330                                    const char *user)
331 {
332         int retval;
333
334         retval = pam_winbind_request(pamh, ctrl, req_type, request, response);
335
336         switch (retval) {
337         case PAM_AUTH_ERR:
338                 /* incorrect password */
339                 _pam_log(pamh, ctrl, LOG_WARNING, "user '%s' denied access (incorrect password or invalid membership)", user);
340                 return retval;
341         case PAM_ACCT_EXPIRED:
342                 /* account expired */
343                 _pam_log(pamh, ctrl, LOG_WARNING, "user '%s' account expired", user);
344                 return retval;
345         case PAM_AUTHTOK_EXPIRED:
346                 /* password expired */
347                 _pam_log(pamh, ctrl, LOG_WARNING, "user '%s' password expired", user);
348                 return retval;
349         case PAM_NEW_AUTHTOK_REQD:
350                 /* new password required */
351                 _pam_log(pamh, ctrl, LOG_WARNING, "user '%s' new password required", user);
352                 return retval;
353         case PAM_USER_UNKNOWN:
354                 /* the user does not exist */
355                 _pam_log_debug(pamh, ctrl, LOG_NOTICE, "user '%s' not found", user);
356                 if (ctrl & WINBIND_UNKNOWN_OK_ARG) {
357                         return PAM_IGNORE;
358                 }        
359                 return retval;
360         case PAM_SUCCESS:
361                 if (req_type == WINBINDD_PAM_AUTH) {
362                         /* Otherwise, the authentication looked good */
363                         _pam_log(pamh, ctrl, LOG_NOTICE, "user '%s' granted access", user);
364                 } else if (req_type == WINBINDD_PAM_CHAUTHTOK) {
365                         /* Otherwise, the authentication looked good */
366                         _pam_log(pamh, ctrl, LOG_NOTICE, "user '%s' password changed", user);
367                 } else { 
368                         /* Otherwise, the authentication looked good */
369                         _pam_log(pamh, ctrl, LOG_NOTICE, "user '%s' OK", user);
370                 }
371         
372                 return retval;
373         default:
374                 /* we don't know anything about this return value */
375                 _pam_log(pamh, ctrl, LOG_ERR, "internal module error (retval = %d, user = '%s')",
376                          retval, user);
377                 return retval;
378         }
379 }
380
381 /* talk to winbindd */
382 static int winbind_auth_request(pam_handle_t * pamh,
383                                 int ctrl, 
384                                 const char *user, 
385                                 const char *pass, 
386                                 const char *member, 
387                                 const char *cctype,
388                                 struct winbindd_response *p_response,
389                                 time_t *pwd_last_set,
390                                 char **user_ret)
391 {
392         struct winbindd_request request;
393         struct winbindd_response response;
394         int ret;
395
396         ZERO_STRUCT(request);
397         ZERO_STRUCT(response);
398
399         if (pwd_last_set) {
400                 *pwd_last_set = 0;
401         }
402
403         strncpy(request.data.auth.user, user, 
404                 sizeof(request.data.auth.user)-1);
405
406         strncpy(request.data.auth.pass, pass, 
407                 sizeof(request.data.auth.pass)-1);
408
409         request.data.auth.krb5_cc_type[0] = '\0';
410         request.data.auth.uid = -1;
411         
412         request.flags = WBFLAG_PAM_INFO3_TEXT | WBFLAG_PAM_CONTACT_TRUSTDOM;
413
414         if (ctrl & WINBIND_KRB5_AUTH) {
415
416                 struct passwd *pwd = NULL;
417
418                 _pam_log_debug(pamh, ctrl, LOG_DEBUG, "enabling krb5 login flag\n"); 
419
420                 request.flags |= WBFLAG_PAM_KRB5 | WBFLAG_PAM_FALLBACK_AFTER_KRB5;
421
422                 pwd = getpwnam(user);
423                 if (pwd == NULL) {
424                         return PAM_USER_UNKNOWN;
425                 }
426                 request.data.auth.uid = pwd->pw_uid;
427         }
428
429         if (ctrl & WINBIND_CACHED_LOGIN) {
430                 _pam_log_debug(pamh, ctrl, LOG_DEBUG, "enabling cached login flag\n"); 
431                 request.flags |= WBFLAG_PAM_CACHED_LOGIN;
432         }
433
434         if (user_ret) {
435                 *user_ret = NULL;
436                 request.flags |= WBFLAG_PAM_UNIX_NAME;
437         }
438
439         if (cctype != NULL) {
440                 strncpy(request.data.auth.krb5_cc_type, cctype, 
441                         sizeof(request.data.auth.krb5_cc_type) - 1);
442                 _pam_log_debug(pamh, ctrl, LOG_DEBUG, "enabling request for a %s krb5 ccache\n", cctype); 
443         }
444
445         request.data.auth.require_membership_of_sid[0] = '\0';
446
447         if (member != NULL) {
448                 strncpy(request.data.auth.require_membership_of_sid, member, 
449                         sizeof(request.data.auth.require_membership_of_sid)-1);
450         }
451
452         /* lookup name? */ 
453         if ( (member != NULL) && (strncmp("S-", member, 2) != 0) ) {
454                 
455                 struct winbindd_request sid_request;
456                 struct winbindd_response sid_response;
457
458                 ZERO_STRUCT(sid_request);
459                 ZERO_STRUCT(sid_response);
460
461                 _pam_log_debug(pamh, ctrl, LOG_DEBUG, "no sid given, looking up: %s\n", member);
462
463                 /* fortunatly winbindd can handle non-separated names */
464                 strncpy(sid_request.data.name.name, member,
465                         sizeof(sid_request.data.name.name) - 1);
466
467                 if (pam_winbind_request_log(pamh, ctrl, WINBINDD_LOOKUPNAME, &sid_request, &sid_response, user)) {
468                         _pam_log(pamh, ctrl, LOG_INFO, "could not lookup name: %s\n", member); 
469                         return PAM_AUTH_ERR;
470                 }
471
472                 member = sid_response.data.sid.sid;
473
474                 strncpy(request.data.auth.require_membership_of_sid, member, 
475                         sizeof(request.data.auth.require_membership_of_sid)-1);
476         }
477         
478         ret = pam_winbind_request_log(pamh, ctrl, WINBINDD_PAM_AUTH, &request, &response, user);
479
480         if (pwd_last_set) {
481                 *pwd_last_set = response.data.auth.info3.pass_last_set_time;
482         }
483
484         if ((ctrl & WINBIND_KRB5_AUTH) && 
485             response.data.auth.krb5ccname[0] != '\0') {
486
487                 char var[PATH_MAX];
488
489                 _pam_log_debug(pamh, ctrl, LOG_DEBUG, "request returned KRB5CCNAME: %s", 
490                                response.data.auth.krb5ccname);
491         
492                 snprintf(var, sizeof(var), "KRB5CCNAME=%s", response.data.auth.krb5ccname);
493         
494                 ret = pam_putenv(pamh, var);
495                 if (ret != PAM_SUCCESS) {
496                         _pam_log(pamh, ctrl, LOG_ERR, "failed to set KRB5CCNAME to %s", var);
497                         return ret;
498                 }
499         }
500
501         if (p_response) {
502                 /* We want to process the response in the caller. */
503                 *p_response = response;
504                 return ret;
505         }
506
507         if (ret) {
508                 PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_PASSWORD_EXPIRED");
509                 PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_PASSWORD_MUST_CHANGE");
510                 PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_INVALID_WORKSTATION");
511                 PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_INVALID_LOGON_HOURS");
512                 PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_ACCOUNT_EXPIRED");
513                 PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_ACCOUNT_DISABLED");
514                 PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_ACCOUNT_LOCKED_OUT");
515                 PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT");
516                 PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_NOLOGON_SERVER_TRUST_ACCOUNT");
517                 PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT");
518                 PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND");
519                 PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_NO_LOGON_SERVERS");
520         }
521
522         /* handle the case where the auth was ok, but the password must expire right now */
523         /* good catch from Ralf Haferkamp: an expiry of "never" is translated to -1 */
524         if ( ! (response.data.auth.info3.acct_flags & ACB_PWNOEXP) &&
525             (response.data.auth.policy.expire > 0) && 
526             (response.data.auth.info3.pass_last_set_time + response.data.auth.policy.expire < time(NULL))) {
527
528                 ret = PAM_AUTHTOK_EXPIRED;
529
530                 _pam_log_debug(pamh, ctrl, LOG_DEBUG,"Password has expired (Password was last set: %d, "
531                                "the policy says it should expire here %d (now it's: %d)\n",
532                                response.data.auth.info3.pass_last_set_time,
533                                response.data.auth.info3.pass_last_set_time + response.data.auth.policy.expire,
534                                time(NULL));
535
536                 PAM_WB_REMARK_DIRECT_RET(pamh, "NT_STATUS_PASSWORD_EXPIRED");
537
538         }
539
540         /* warn a user if the password is about to expire soon */
541         if ( ! (response.data.auth.info3.acct_flags & ACB_PWNOEXP) &&
542             (response.data.auth.policy.expire) && 
543             (response.data.auth.info3.pass_last_set_time + response.data.auth.policy.expire > time(NULL) ) ) {
544
545                 int days = (response.data.auth.info3.pass_last_set_time + response.data.auth.policy.expire -
546                             time(NULL))/ SECONDS_PER_DAY;
547                 if (days <= DAYS_TO_WARN_BEFORE_PWD_EXPIRES) {
548                         _make_remark_format(pamh, PAM_TEXT_INFO, "Your password will expire in %d days", days);
549                 }
550         }
551
552         if (response.data.auth.info3.user_flgs & LOGON_CACHED_ACCOUNT) {
553                 _make_remark(pamh, PAM_ERROR_MSG, "Logging on using cached account. Network ressources can be unavailable");
554                 _pam_log_debug(pamh, ctrl, LOG_DEBUG,"User %s logged on using cached account\n", user);
555         }
556
557         /* save the CIFS homedir for pam_cifs / pam_mount */
558         if (response.data.auth.info3.home_dir[0] != '\0') {
559
560                 int ret2 = pam_set_data(pamh, PAM_WINBIND_HOMEDIR,
561                                         (void *) strdup(response.data.auth.info3.home_dir),
562                                         _pam_winbind_cleanup_func);
563                 if (ret2) {
564                         _pam_log_debug(pamh, ctrl, LOG_DEBUG, "Could not set data: %s", 
565                                        pam_strerror(pamh, ret2));
566                 }
567
568         }
569
570         /* save the logon script path for other PAM modules */
571         if (response.data.auth.info3.logon_script[0] != '\0') {
572
573                 int ret2 = pam_set_data(pamh, PAM_WINBIND_LOGONSCRIPT, 
574                                         (void *) strdup(response.data.auth.info3.logon_script), 
575                                         _pam_winbind_cleanup_func);
576                 if (ret2) {
577                         _pam_log_debug(pamh, ctrl, LOG_DEBUG, "Could not set data: %s", 
578                                        pam_strerror(pamh, ret2));
579                 }
580         }
581
582         /* save the profile path for other PAM modules */
583         if (response.data.auth.info3.profile_path[0] != '\0') {
584
585                 int ret2 = pam_set_data(pamh, PAM_WINBIND_PROFILEPATH, 
586                                         (void *) strdup(response.data.auth.info3.profile_path), 
587                                         _pam_winbind_cleanup_func);
588                 if (ret2) {
589                         _pam_log_debug(pamh, ctrl, LOG_DEBUG, "Could not set data: %s", 
590                                        pam_strerror(pamh, ret2));
591                 }
592         }
593
594         /* If winbindd returned a username, return the pointer to it here. */
595         if (user_ret && response.extra_data.data) {
596                 /* We have to trust it's a null terminated string. */
597                 *user_ret = (char *)response.extra_data.data;
598         }
599
600         return ret;
601 }
602
603 /* talk to winbindd */
604 static int winbind_chauthtok_request(pam_handle_t * pamh,
605                                      int ctrl,
606                                      const char *user, 
607                                      const char *oldpass,
608                                      const char *newpass,
609                                      time_t pwd_last_set) 
610 {
611         struct winbindd_request request;
612         struct winbindd_response response;
613         int ret;
614
615         ZERO_STRUCT(request);
616         ZERO_STRUCT(response);
617
618         if (request.data.chauthtok.user == NULL) return -2;
619
620         strncpy(request.data.chauthtok.user, user, 
621                 sizeof(request.data.chauthtok.user) - 1);
622
623         if (oldpass != NULL) {
624                 strncpy(request.data.chauthtok.oldpass, oldpass, 
625                         sizeof(request.data.chauthtok.oldpass) - 1);
626         } else {
627                 request.data.chauthtok.oldpass[0] = '\0';
628         }
629         
630         if (newpass != NULL) {
631                 strncpy(request.data.chauthtok.newpass, newpass, 
632                         sizeof(request.data.chauthtok.newpass) - 1);
633         } else {
634                 request.data.chauthtok.newpass[0] = '\0';
635         }
636
637         if (ctrl & WINBIND_KRB5_AUTH) {
638                 request.flags = WBFLAG_PAM_KRB5 | WBFLAG_PAM_CONTACT_TRUSTDOM;
639         }
640
641         ret = pam_winbind_request_log(pamh, ctrl, WINBINDD_PAM_CHAUTHTOK, &request, &response, user);
642
643         if (ret == PAM_SUCCESS) {
644                 return ret;
645         }
646
647         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_BACKUP_CONTROLLER");
648         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND");
649         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_NO_LOGON_SERVERS");
650         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_ACCESS_DENIED");
651
652         /* TODO: tell the min pwd length ? */
653         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_PWD_TOO_SHORT");
654
655         /* TODO: tell the minage ? */
656         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_PWD_TOO_RECENT");
657
658         /* TODO: tell the history length ? */
659         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh, response, "NT_STATUS_PWD_HISTORY_CONFLICT");
660
661         if (!strcasecmp(response.data.auth.nt_status_string, "NT_STATUS_PASSWORD_RESTRICTION")) {
662
663                 /* FIXME: avoid to send multiple PAM messages after another */
664                 switch (response.data.auth.reject_reason) {
665                         case -1:
666                                 break;
667                         case REJECT_REASON_OTHER:
668                                 if ((response.data.auth.policy.min_passwordage > 0) &&
669                                     (pwd_last_set + response.data.auth.policy.min_passwordage > time(NULL))) {
670                                         PAM_WB_REMARK_DIRECT(pamh, "NT_STATUS_PWD_TOO_RECENT");
671                                 }
672                                 break;
673                         case REJECT_REASON_TOO_SHORT:
674                                 PAM_WB_REMARK_DIRECT(pamh, "NT_STATUS_PWD_TOO_SHORT");
675                                 break;
676                         case REJECT_REASON_IN_HISTORY:
677                                 PAM_WB_REMARK_DIRECT(pamh, "NT_STATUS_PWD_HISTORY_CONFLICT");
678                                 break;
679                         case REJECT_REASON_NOT_COMPLEX:
680                                 _make_remark(pamh, PAM_ERROR_MSG, "Password does not meet complexity requirements");
681                                 break;
682                         default:
683                                 _pam_log_debug(pamh, ctrl, LOG_DEBUG,
684                                                "unknown password change reject reason: %d", 
685                                                response.data.auth.reject_reason);
686                                 break;
687                 }
688
689                 _make_remark_format(pamh, PAM_ERROR_MSG,  
690                         "Your password must be at least %d characters; "
691                         "cannot repeat any of the your previous %d passwords"
692                         "%s. "
693                         "Please type a different password. "
694                         "Type a password which meets these requirements in both text boxes.",
695                         response.data.auth.policy.min_length_password,
696                         response.data.auth.policy.password_history,
697                         (response.data.auth.policy.password_properties & DOMAIN_PASSWORD_COMPLEX) ? 
698                                 "; must contain capitals, numerals or punctuation; and cannot contain your account or full name" : 
699                                 "");
700
701         }
702
703         return ret;
704 }
705
706 /*
707  * Checks if a user has an account
708  *
709  * return values:
710  *       1  = User not found
711  *       0  = OK
712  *      -1  = System error
713  */
714 static int valid_user(pam_handle_t *pamh, int ctrl, const char *user)
715 {
716         /* check not only if the user is available over NSS calls, also make
717          * sure it's really a winbind user, this is important when stacking PAM
718          * modules in the 'account' or 'password' facility. */
719
720         struct passwd *pwd = NULL;
721         struct winbindd_request request;
722         struct winbindd_response response;
723         int ret;
724
725         ZERO_STRUCT(request);
726         ZERO_STRUCT(response);
727
728         pwd = getpwnam(user);
729         if (pwd == NULL) {
730                 return 1;
731         }
732
733         strncpy(request.data.username, user,
734                 sizeof(request.data.username) - 1);
735
736         ret = pam_winbind_request_log(pamh, ctrl, WINBINDD_GETPWNAM, &request, &response, user);
737
738         switch (ret) {
739                 case PAM_USER_UNKNOWN:
740                         return 1;
741                 case PAM_SUCCESS:
742                         return 0;
743                 default:
744                         break;
745         }
746         return -1;
747 }
748
749 static char *_pam_delete(register char *xx)
750 {
751         _pam_overwrite(xx);
752         _pam_drop(xx);
753         return NULL;
754 }
755
756 /*
757  * obtain a password from the user
758  */
759
760 static int _winbind_read_password(pam_handle_t * pamh,
761                                   unsigned int ctrl,
762                                   const char *comment,
763                                   const char *prompt1,
764                                   const char *prompt2,
765                                   const char **pass)
766 {
767         int authtok_flag;
768         int retval;
769         const char *item;
770         char *token;
771
772         /*
773          * make sure nothing inappropriate gets returned
774          */
775
776         *pass = token = NULL;
777
778         /*
779          * which authentication token are we getting?
780          */
781
782         authtok_flag = on(WINBIND__OLD_PASSWORD, ctrl) ? PAM_OLDAUTHTOK : PAM_AUTHTOK;
783
784         /*
785          * should we obtain the password from a PAM item ?
786          */
787
788         if (on(WINBIND_TRY_FIRST_PASS_ARG, ctrl) || on(WINBIND_USE_FIRST_PASS_ARG, ctrl)) {
789                 retval = _pam_get_item(pamh, authtok_flag, &item);
790                 if (retval != PAM_SUCCESS) {
791                         /* very strange. */
792                         _pam_log(pamh, ctrl, LOG_ALERT, 
793                                  "pam_get_item returned error to unix-read-password"
794                             );
795                         return retval;
796                 } else if (item != NULL) {      /* we have a password! */
797                         *pass = item;
798                         item = NULL;
799                         return PAM_SUCCESS;
800                 } else if (on(WINBIND_USE_FIRST_PASS_ARG, ctrl)) {
801                         return PAM_AUTHTOK_RECOVER_ERR;         /* didn't work */
802                 } else if (on(WINBIND_USE_AUTHTOK_ARG, ctrl)
803                            && off(WINBIND__OLD_PASSWORD, ctrl)) {
804                         return PAM_AUTHTOK_RECOVER_ERR;
805                 }
806         }
807         /*
808          * getting here implies we will have to get the password from the
809          * user directly.
810          */
811
812         {
813                 struct pam_message msg[3], *pmsg[3];
814                 struct pam_response *resp;
815                 int i, replies;
816
817                 /* prepare to converse */
818
819                 if (comment != NULL) {
820                         pmsg[0] = &msg[0];
821                         msg[0].msg_style = PAM_TEXT_INFO;
822                         msg[0].msg = CONST_DISCARD(char *, comment);
823                         i = 1;
824                 } else {
825                         i = 0;
826                 }
827
828                 pmsg[i] = &msg[i];
829                 msg[i].msg_style = PAM_PROMPT_ECHO_OFF;
830                 msg[i++].msg = CONST_DISCARD(char *, prompt1);
831                 replies = 1;
832
833                 if (prompt2 != NULL) {
834                         pmsg[i] = &msg[i];
835                         msg[i].msg_style = PAM_PROMPT_ECHO_OFF;
836                         msg[i++].msg = CONST_DISCARD(char *, prompt2);
837                         ++replies;
838                 }
839                 /* so call the conversation expecting i responses */
840                 resp = NULL;
841                 retval = converse(pamh, i, pmsg, &resp);
842
843                 if (resp != NULL) {
844
845                         /* interpret the response */
846
847                         if (retval == PAM_SUCCESS) {    /* a good conversation */
848
849                                 token = x_strdup(resp[i - replies].resp);
850                                 if (token != NULL) {
851                                         if (replies == 2) {
852                                                 /* verify that password entered correctly */
853                                                 if (!resp[i - 1].resp
854                                                     || strcmp(token, resp[i - 1].resp)) {
855                                                         _pam_delete(token);     /* mistyped */
856                                                         retval = PAM_AUTHTOK_RECOVER_ERR;
857                                                         _make_remark(pamh, PAM_ERROR_MSG, MISTYPED_PASS);
858                                                 }
859                                         }
860                                 } else {
861                                         _pam_log(pamh, ctrl, LOG_NOTICE, "could not recover authentication token");
862                                         retval = PAM_AUTHTOK_RECOVER_ERR;
863                                 }
864
865                         }
866                         /*
867                          * tidy up the conversation (resp_retcode) is ignored
868                          * -- what is it for anyway? AGM
869                          */
870
871                         _pam_drop_reply(resp, i);
872
873                 } else {
874                         retval = (retval == PAM_SUCCESS)
875                             ? PAM_AUTHTOK_RECOVER_ERR : retval;
876                 }
877         }
878
879         if (retval != PAM_SUCCESS) {
880                 _pam_log_debug(pamh, ctrl, LOG_DEBUG,
881                                  "unable to obtain a password");
882                 return retval;
883         }
884         /* 'token' is the entered password */
885
886         /* we store this password as an item */
887         
888         retval = pam_set_item(pamh, authtok_flag, token);
889         _pam_delete(token);     /* clean it up */
890         if (retval != PAM_SUCCESS || 
891             (retval = _pam_get_item(pamh, authtok_flag, &item)) != PAM_SUCCESS) {
892                 
893                 _pam_log(pamh, ctrl, LOG_CRIT, "error manipulating password");
894                 return retval;
895                 
896         }
897
898         *pass = item;
899         item = NULL;            /* break link to password */
900
901         return PAM_SUCCESS;
902 }
903
904 const char *get_conf_item_string(const pam_handle_t *pamh,
905                                  int argc, 
906                                  const char **argv, 
907                                  int ctrl,
908                                  dictionary *d,
909                                  const char *item, 
910                                  int config_flag)
911 {
912         int i = 0;
913         const char *parm_opt = NULL;
914         char *key = NULL;
915
916         if (!(ctrl & config_flag)) {
917                 goto out;
918         }
919
920         /* let the pam opt take precedence over the pam_winbind.conf option */
921
922         if (d != NULL) {
923
924                 if (!asprintf(&key, "global:%s", item)) {
925                         goto out;
926                 }
927
928                 parm_opt = iniparser_getstr(d, key);
929                 SAFE_FREE(key);
930         }
931
932         for ( i=0; i<argc; i++ ) {
933
934                 if ((strncmp(argv[i], item, strlen(item)) == 0)) {
935                         char *p;
936
937                         if ( (p = strchr( argv[i], '=' )) == NULL) {
938                                 _pam_log(pamh, ctrl, LOG_INFO, "no \"=\" delimiter for \"%s\" found\n", item);
939                                 goto out;
940                         }
941                         _pam_log_debug(pamh, ctrl, LOG_INFO, "PAM config: %s '%s'\n", item, p+1);
942                         return p + 1;
943                 }
944         }
945
946         if (d != NULL) {
947                 _pam_log_debug(pamh, ctrl, LOG_INFO, "CONFIG file: %s '%s'\n", item, parm_opt);
948         }
949 out:
950         return parm_opt;
951 }
952
953 const char *get_krb5_cc_type_from_config(const pam_handle_t *pamh, int argc, const char **argv, int ctrl, dictionary *d)
954 {
955         return get_conf_item_string(pamh, argc, argv, ctrl, d, "krb5_ccache_type", WINBIND_KRB5_CCACHE_TYPE);
956 }
957
958 const char *get_member_from_config(const pam_handle_t *pamh, int argc, const char **argv, int ctrl, dictionary *d)
959 {
960         const char *ret = NULL;
961         ret = get_conf_item_string(pamh, argc, argv, ctrl, d, "require_membership_of", WINBIND_REQUIRED_MEMBERSHIP);
962         if (ret) {
963                 return ret;
964         }
965         return get_conf_item_string(pamh, argc, argv, ctrl, d, "require-membership-of", WINBIND_REQUIRED_MEMBERSHIP);
966 }
967
968 PAM_EXTERN
969 int pam_sm_authenticate(pam_handle_t *pamh, int flags,
970                         int argc, const char **argv)
971 {
972         const char *username;
973         const char *password;
974         const char *member = NULL;
975         const char *cctype = NULL;
976         int retval = PAM_AUTH_ERR;
977         dictionary *d = NULL;
978         char *username_ret = NULL;
979
980         /* parse arguments */
981         int ctrl = _pam_parse(pamh, flags, argc, argv, &d);
982         if (ctrl == -1) {
983                 retval = PAM_SYSTEM_ERR;
984                 goto out;
985         }
986
987         _pam_log_debug(pamh, ctrl, LOG_DEBUG, "pam_winbind: pam_sm_authenticate (flags: 0x%04x)", flags);
988
989         /* Get the username */
990         retval = pam_get_user(pamh, &username, NULL);
991         if ((retval != PAM_SUCCESS) || (!username)) {
992                 _pam_log_debug(pamh, ctrl, LOG_DEBUG, "can not get the username");
993                 retval = PAM_SERVICE_ERR;
994                 goto out;
995         }
996
997         retval = _winbind_read_password(pamh, ctrl, NULL, 
998                                         "Password: ", NULL,
999                                         &password);
1000
1001         if (retval != PAM_SUCCESS) {
1002                 _pam_log(pamh, ctrl, LOG_ERR, "Could not retrieve user's password");
1003                 retval = PAM_AUTHTOK_ERR;
1004                 goto out;
1005         }
1006
1007         /* Let's not give too much away in the log file */
1008
1009 #ifdef DEBUG_PASSWORD
1010         _pam_log_debug(pamh, ctrl, LOG_INFO, "Verify user '%s' with password '%s'", 
1011                        username, password);
1012 #else
1013         _pam_log_debug(pamh, ctrl, LOG_INFO, "Verify user '%s'", username);
1014 #endif
1015
1016         member = get_member_from_config(pamh, argc, argv, ctrl, d);
1017
1018         cctype = get_krb5_cc_type_from_config(pamh, argc, argv, ctrl, d);
1019
1020         /* Now use the username to look up password */
1021         retval = winbind_auth_request(pamh, ctrl, username, password, member,
1022                                       cctype, NULL, NULL, &username_ret);
1023
1024         if (retval == PAM_NEW_AUTHTOK_REQD ||
1025             retval == PAM_AUTHTOK_EXPIRED) {
1026
1027                 char *buf;
1028
1029                 if (!asprintf(&buf, "%d", retval)) {
1030                         retval = PAM_BUF_ERR;
1031                         goto out;
1032                 }
1033
1034                 pam_set_data( pamh, PAM_WINBIND_NEW_AUTHTOK_REQD, (void *)buf, _pam_winbind_cleanup_func);
1035
1036                 retval = PAM_SUCCESS;
1037                 goto out;
1038         }
1039
1040 out:
1041         if (username_ret) {
1042                 pam_set_item (pamh, PAM_USER, username_ret);
1043                 _pam_log_debug(pamh, ctrl, LOG_INFO, "Returned user was '%s'", username_ret);
1044                 free(username_ret);
1045         }
1046
1047         if (d) {
1048                 iniparser_freedict(d);
1049         }
1050         return retval;
1051 }
1052
1053 PAM_EXTERN
1054 int pam_sm_setcred(pam_handle_t *pamh, int flags,
1055                    int argc, const char **argv)
1056 {
1057         dictionary *d = NULL;
1058
1059         /* parse arguments */
1060         int ctrl = _pam_parse(pamh, flags, argc, argv, &d);
1061         if (ctrl == -1) {
1062                 return PAM_SYSTEM_ERR;
1063         }
1064
1065         _pam_log_debug(pamh, ctrl, LOG_DEBUG, "pam_winbind: pam_sm_setcred (flags: 0x%04x)", flags);
1066
1067         if (d) {
1068                 iniparser_freedict(d);
1069         }
1070
1071         if (flags & PAM_DELETE_CRED) {
1072                 return pam_sm_close_session(pamh, flags, argc, argv);
1073         }
1074
1075         return PAM_SUCCESS;
1076 }
1077
1078 /*
1079  * Account management. We want to verify that the account exists 
1080  * before returning PAM_SUCCESS
1081  */
1082 PAM_EXTERN
1083 int pam_sm_acct_mgmt(pam_handle_t *pamh, int flags,
1084                    int argc, const char **argv)
1085 {
1086         const char *username;
1087         int retval = PAM_USER_UNKNOWN;
1088         void *tmp = NULL;
1089
1090         /* parse arguments */
1091         int ctrl = _pam_parse(pamh, flags, argc, argv, NULL);
1092         if (ctrl == -1) {
1093                 return PAM_SYSTEM_ERR;
1094         }
1095
1096         _pam_log_debug(pamh, ctrl, LOG_DEBUG, "pam_winbind: pam_sm_acct_mgmt (flags: 0x%04x)", flags);
1097
1098
1099         /* Get the username */
1100         retval = pam_get_user(pamh, &username, NULL);
1101         if ((retval != PAM_SUCCESS) || (!username)) {
1102                 _pam_log_debug(pamh, ctrl, LOG_DEBUG,"can not get the username");
1103                 return PAM_SERVICE_ERR;
1104         }
1105
1106         /* Verify the username */
1107         retval = valid_user(pamh, ctrl, username);
1108         switch (retval) {
1109         case -1:
1110                 /* some sort of system error. The log was already printed */
1111                 return PAM_SERVICE_ERR;
1112         case 1:
1113                 /* the user does not exist */
1114                 _pam_log_debug(pamh, ctrl, LOG_NOTICE, "user '%s' not found", username);
1115                 if (ctrl & WINBIND_UNKNOWN_OK_ARG) {
1116                         return PAM_IGNORE;
1117                 }
1118                 return PAM_USER_UNKNOWN;
1119         case 0:
1120                 pam_get_data( pamh, PAM_WINBIND_NEW_AUTHTOK_REQD, (const void **)&tmp);
1121                 if (tmp != NULL) {
1122                         retval = atoi((const char *)tmp);
1123                         switch (retval) {
1124                         case PAM_AUTHTOK_EXPIRED:
1125                                 /* fall through, since new token is required in this case */
1126                         case PAM_NEW_AUTHTOK_REQD:
1127                                 _pam_log(pamh, ctrl, LOG_WARNING, "pam_sm_acct_mgmt success but %s is set", 
1128                                          PAM_WINBIND_NEW_AUTHTOK_REQD);
1129                                 _pam_log(pamh, ctrl, LOG_NOTICE, "user '%s' needs new password", username);
1130                                 /* PAM_AUTHTOKEN_REQD does not exist, but is documented in the manpage */
1131                                 return PAM_NEW_AUTHTOK_REQD; 
1132                         default:
1133                                 _pam_log(pamh, ctrl, LOG_WARNING, "pam_sm_acct_mgmt success");
1134                                 _pam_log(pamh, ctrl, LOG_NOTICE, "user '%s' granted access", username);
1135                                 return PAM_SUCCESS;
1136                         }
1137                 }
1138
1139                 /* Otherwise, the authentication looked good */
1140                 _pam_log(pamh, ctrl, LOG_NOTICE, "user '%s' granted access", username);
1141                 return PAM_SUCCESS;
1142         default:
1143                 /* we don't know anything about this return value */
1144                 _pam_log(pamh, ctrl, LOG_ERR, "internal module error (retval = %d, user = '%s')", 
1145                          retval, username);
1146                 return PAM_SERVICE_ERR;
1147         }
1148
1149         /* should not be reached */
1150         return PAM_IGNORE;
1151 }
1152
1153 PAM_EXTERN
1154 int pam_sm_open_session(pam_handle_t *pamh, int flags,
1155                         int argc, const char **argv)
1156 {
1157         /* parse arguments */
1158         int ctrl = _pam_parse(pamh, flags, argc, argv, NULL);
1159         if (ctrl == -1) {
1160                 return PAM_SYSTEM_ERR;
1161         }
1162
1163         _pam_log_debug(pamh, ctrl, LOG_DEBUG, "pam_winbind: pam_sm_open_session handler (flags: 0x%04x)", flags);
1164
1165         return PAM_SUCCESS;
1166 }
1167
1168 PAM_EXTERN
1169 int pam_sm_close_session(pam_handle_t *pamh, int flags,
1170                          int argc, const char **argv)
1171 {
1172         dictionary *d = NULL;
1173         int retval = PAM_SUCCESS;
1174
1175         /* parse arguments */
1176         int ctrl = _pam_parse(pamh, flags, argc, argv, &d);
1177         if (ctrl == -1) {
1178                 retval = PAM_SYSTEM_ERR;
1179                 goto out;
1180         }
1181
1182         _pam_log_debug(pamh, ctrl, LOG_DEBUG, "pam_winbind: pam_sm_close_session handler (flags: 0x%04x)", flags);
1183
1184         if (!(flags & PAM_DELETE_CRED)) {
1185                 retval = PAM_SUCCESS;
1186                 goto out;
1187         }
1188
1189         if (ctrl & WINBIND_KRB5_AUTH) {
1190
1191                 /* destroy the ccache here */
1192                 struct winbindd_request request;
1193                 struct winbindd_response response;
1194                 const char *user;
1195                 const char *ccname = NULL;
1196                 struct passwd *pwd = NULL;
1197
1198                 ZERO_STRUCT(request);
1199                 ZERO_STRUCT(response);
1200
1201                 retval = pam_get_user(pamh, &user, "Username: ");
1202                 if (retval == PAM_SUCCESS) {
1203                         if (user == NULL) {
1204                                 _pam_log(pamh, ctrl, LOG_ERR, "username was NULL!");
1205                                 retval = PAM_USER_UNKNOWN;
1206                                 goto out;
1207                         }
1208                         if (retval == PAM_SUCCESS) {
1209                                 _pam_log_debug(pamh, ctrl, LOG_DEBUG, "username [%s] obtained", user);
1210                         }
1211                 } else {
1212                         _pam_log_debug(pamh, ctrl, LOG_DEBUG, "could not identify user");
1213                         goto out;
1214                 }
1215
1216                 ccname = pam_getenv(pamh, "KRB5CCNAME");
1217                 if (ccname == NULL) {
1218                         _pam_log_debug(pamh, ctrl, LOG_DEBUG, "user has no KRB5CCNAME environment");
1219                 }
1220
1221                 strncpy(request.data.logoff.user, user,
1222                         sizeof(request.data.logoff.user) - 1);
1223
1224                 if (ccname) {
1225                         strncpy(request.data.logoff.krb5ccname, ccname,
1226                                 sizeof(request.data.logoff.krb5ccname) - 1);
1227                 }
1228
1229                 pwd = getpwnam(user);
1230                 if (pwd == NULL) {
1231                         retval = PAM_USER_UNKNOWN;
1232                         goto out;
1233                 }
1234                 request.data.logoff.uid = pwd->pw_uid;
1235
1236                 request.flags = WBFLAG_PAM_KRB5 | WBFLAG_PAM_CONTACT_TRUSTDOM;
1237
1238                 retval = pam_winbind_request_log(pamh, ctrl, WINBINDD_PAM_LOGOFF, &request, &response, user);
1239         }
1240
1241 out:
1242         if (d) {
1243                 iniparser_freedict(d);
1244         }
1245         return retval;
1246 }
1247
1248
1249
1250 PAM_EXTERN 
1251 int pam_sm_chauthtok(pam_handle_t * pamh, int flags,
1252                      int argc, const char **argv)
1253 {
1254         unsigned int lctrl;
1255         int ret;
1256         unsigned int ctrl;
1257
1258         /* <DO NOT free() THESE> */
1259         const char *user;
1260         char *pass_old, *pass_new;
1261         /* </DO NOT free() THESE> */
1262
1263         char *Announce;
1264         
1265         int retry = 0;
1266         dictionary *d = NULL;
1267
1268         ctrl = _pam_parse(pamh, flags, argc, argv, &d);
1269         if (ctrl == -1) {
1270                 ret = PAM_SYSTEM_ERR;
1271                 goto out;
1272         }
1273
1274         _pam_log_debug(pamh, ctrl, LOG_DEBUG, "pam_winbind: pam_sm_chauthtok (flags: 0x%04x)", flags);
1275
1276         /* clearing offline bit for the auth in the password change */
1277         ctrl &= ~WINBIND_CACHED_LOGIN;
1278
1279         /*
1280          * First get the name of a user
1281          */
1282         ret = pam_get_user(pamh, &user, "Username: ");
1283         if (ret == PAM_SUCCESS) {
1284                 if (user == NULL) {
1285                         _pam_log(pamh, ctrl, LOG_ERR, "username was NULL!");
1286                         ret = PAM_USER_UNKNOWN;
1287                         goto out;
1288                 }
1289                 if (ret == PAM_SUCCESS) {
1290                         _pam_log_debug(pamh, ctrl, LOG_DEBUG, "username [%s] obtained",
1291                                  user);
1292                 }
1293         } else {
1294                 _pam_log_debug(pamh, ctrl, LOG_DEBUG,
1295                          "password - could not identify user");
1296                 goto out;
1297         }
1298
1299         /* check if this is really a user in winbindd, not only in NSS */
1300         ret = valid_user(pamh, ctrl, user);
1301         switch (ret) {
1302                 case 1:
1303                         ret = PAM_USER_UNKNOWN;
1304                         goto out;
1305                 case -1:
1306                         ret = PAM_SYSTEM_ERR;
1307                         goto out;
1308                 default:
1309                         break;
1310         }
1311                 
1312         /*
1313          * obtain and verify the current password (OLDAUTHTOK) for
1314          * the user.
1315          */
1316
1317         if (flags & PAM_PRELIM_CHECK) {
1318                 struct winbindd_response response;
1319                 time_t pwdlastset_prelim = 0;
1320                 
1321                 /* instruct user what is happening */
1322 #define greeting "Changing password for "
1323                 Announce = (char *) malloc(sizeof(greeting) + strlen(user));
1324                 if (Announce == NULL) {
1325                         _pam_log(pamh, ctrl, LOG_CRIT, "password - out of memory");
1326                         ret = PAM_BUF_ERR;
1327                         goto out;
1328                 }
1329                 (void) strcpy(Announce, greeting);
1330                 (void) strcpy(Announce + sizeof(greeting) - 1, user);
1331 #undef greeting
1332                 
1333                 lctrl = ctrl | WINBIND__OLD_PASSWORD;
1334                 ret = _winbind_read_password(pamh, lctrl,
1335                                                 Announce,
1336                                                 "(current) NT password: ",
1337                                                 NULL,
1338                                                 (const char **) &pass_old);
1339                 if (ret != PAM_SUCCESS) {
1340                         _pam_log(pamh, ctrl, LOG_NOTICE, "password - (old) token not obtained");
1341                         goto out;
1342                 }
1343
1344                 /* We don't need krb5 env set for password change test. */
1345                 ctrl &= ~WINBIND_KRB5_AUTH;
1346
1347                 /* verify that this is the password for this user */
1348                 
1349                 ret = winbind_auth_request(pamh, ctrl, user, pass_old,
1350                                         NULL, NULL, &response, &pwdlastset_prelim, NULL);
1351
1352                 if (ret != PAM_ACCT_EXPIRED && 
1353                     ret != PAM_AUTHTOK_EXPIRED &&
1354                     ret != PAM_NEW_AUTHTOK_REQD &&
1355                     ret != PAM_SUCCESS) {
1356                         pass_old = NULL;
1357                         if (d) {
1358                                 iniparser_freedict(d);
1359                         }
1360                         /* Deal with offline errors. */
1361                         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh,
1362                                                 response,
1363                                                 "NT_STATUS_NO_LOGON_SERVERS");
1364                         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh,
1365                                                 response,
1366                                                 "NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND");
1367                         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh,
1368                                                 response,
1369                                                 "NT_STATUS_ACCESS_DENIED");
1370                         return ret;
1371                 }
1372                 
1373                 pam_set_data(pamh, PAM_WINBIND_PWD_LAST_SET, (void *)pwdlastset_prelim, NULL);
1374
1375                 ret = pam_set_item(pamh, PAM_OLDAUTHTOK, (const void *) pass_old);
1376                 pass_old = NULL;
1377                 if (ret != PAM_SUCCESS) {
1378                         _pam_log(pamh, ctrl, LOG_CRIT, "failed to set PAM_OLDAUTHTOK");
1379                 }
1380         } else if (flags & PAM_UPDATE_AUTHTOK) {
1381         
1382                 time_t pwdlastset_update = 0;
1383                 
1384                 /*
1385                  * obtain the proposed password
1386                  */
1387                 
1388                 /*
1389                  * get the old token back. 
1390                  */
1391                 
1392                 ret = _pam_get_item(pamh, PAM_OLDAUTHTOK, &pass_old);
1393                 
1394                 if (ret != PAM_SUCCESS) {
1395                         _pam_log(pamh, ctrl, LOG_NOTICE, "user not authenticated");
1396                         goto out;
1397                 }
1398                 
1399                 lctrl = ctrl;
1400                 
1401                 if (on(WINBIND_USE_AUTHTOK_ARG, lctrl)) {
1402                         lctrl |= WINBIND_USE_FIRST_PASS_ARG;
1403                 }
1404                 retry = 0;
1405                 ret = PAM_AUTHTOK_ERR;
1406                 while ((ret != PAM_SUCCESS) && (retry++ < MAX_PASSWD_TRIES)) {
1407                         /*
1408                          * use_authtok is to force the use of a previously entered
1409                          * password -- needed for pluggable password strength checking
1410                          */
1411                         
1412                         ret = _winbind_read_password(pamh, lctrl,
1413                                                         NULL,
1414                                                         "Enter new NT password: ",
1415                                                         "Retype new NT password: ",
1416                                                         (const char **) &pass_new);
1417                         
1418                         if (ret != PAM_SUCCESS) {
1419                                 _pam_log_debug(pamh, ctrl, LOG_ALERT
1420                                          ,"password - new password not obtained");
1421                                 pass_old = NULL;/* tidy up */
1422                                 goto out;
1423                         }
1424
1425                         /*
1426                          * At this point we know who the user is and what they
1427                          * propose as their new password. Verify that the new
1428                          * password is acceptable.
1429                          */
1430                         
1431                         if (pass_new[0] == '\0') {/* "\0" password = NULL */
1432                                 pass_new = NULL;
1433                         }
1434                 }
1435                 
1436                 /*
1437                  * By reaching here we have approved the passwords and must now
1438                  * rebuild the password database file.
1439                  */
1440                 _pam_get_data( pamh, PAM_WINBIND_PWD_LAST_SET,
1441                                &pwdlastset_update);
1442
1443                 ret = winbind_chauthtok_request(pamh, ctrl, user, pass_old, pass_new, pwdlastset_update);
1444                 if (ret) {
1445                         _pam_overwrite(pass_new);
1446                         _pam_overwrite(pass_old);
1447                         pass_old = pass_new = NULL;
1448                         goto out;
1449                 }
1450
1451                 /* just in case we need krb5 creds after a password change over msrpc */
1452
1453                 if (ctrl & WINBIND_KRB5_AUTH) {
1454                         struct winbindd_response response;
1455
1456                         const char *member = get_member_from_config(pamh, argc, argv, ctrl, d);
1457                         const char *cctype = get_krb5_cc_type_from_config(pamh, argc, argv, ctrl, d);
1458
1459                         ret = winbind_auth_request(pamh, ctrl, user, pass_new,
1460                                                         member, cctype, &response, NULL, NULL);
1461                         _pam_overwrite(pass_new);
1462                         _pam_overwrite(pass_old);
1463                         pass_old = pass_new = NULL;
1464                         if (d) {
1465                                 iniparser_freedict(d);
1466                         }
1467                         /* Deal with offline errors. */
1468                         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh,
1469                                                 response,
1470                                                 "NT_STATUS_NO_LOGON_SERVERS");
1471                         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh,
1472                                                 response,
1473                                                 "NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND");
1474                         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh,
1475                                                 response,
1476                                                 "NT_STATUS_ACCESS_DENIED");
1477                         return ret;
1478                 }
1479         } else {
1480                 ret = PAM_SERVICE_ERR;
1481         }
1482
1483 out:
1484         if (d) {
1485                 iniparser_freedict(d);
1486         }
1487         return ret;
1488 }
1489
1490 #ifdef PAM_STATIC
1491
1492 /* static module data */
1493
1494 struct pam_module _pam_winbind_modstruct = {
1495         MODULE_NAME,
1496         pam_sm_authenticate,
1497         pam_sm_setcred,
1498         pam_sm_acct_mgmt,
1499         pam_sm_open_session,
1500         pam_sm_close_session,
1501         pam_sm_chauthtok
1502 };
1503
1504 #endif
1505
1506 /*
1507  * Copyright (c) Andrew Tridgell  <tridge@samba.org>   2000
1508  * Copyright (c) Tim Potter       <tpot@samba.org>     2000
1509  * Copyright (c) Andrew Bartlettt <abartlet@samba.org> 2002
1510  * Copyright (c) Guenther Deschner <gd@samba.org>      2005-2006
1511  * Copyright (c) Jan Rêkorajski 1999.
1512  * Copyright (c) Andrew G. Morgan 1996-8.
1513  * Copyright (c) Alex O. Yuriev, 1996.
1514  * Copyright (c) Cristian Gafton 1996.
1515  * Copyright (C) Elliot Lee <sopwith@redhat.com> 1996, Red Hat Software. 
1516  *
1517  * Redistribution and use in source and binary forms, with or without
1518  * modification, are permitted provided that the following conditions
1519  * are met:
1520  * 1. Redistributions of source code must retain the above copyright
1521  *    notice, and the entire permission notice in its entirety,
1522  *    including the disclaimer of warranties.
1523  * 2. Redistributions in binary form must reproduce the above copyright
1524  *    notice, this list of conditions and the following disclaimer in the
1525  *    documentation and/or other materials provided with the distribution.
1526  * 3. The name of the author may not be used to endorse or promote
1527  *    products derived from this software without specific prior
1528  *    written permission.
1529  *
1530  * ALTERNATIVELY, this product may be distributed under the terms of
1531  * the GNU Public License, in which case the provisions of the GPL are
1532  * required INSTEAD OF the above restrictions.  (This clause is
1533  * necessary due to a potential bad interaction between the GPL and
1534  * the restrictions contained in a BSD-style copyright.)
1535  *
1536  * THIS SOFTWARE IS PROVIDED `AS IS'' AND ANY EXPRESS OR IMPLIED
1537  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
1538  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
1539  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
1540  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
1541  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
1542  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
1543  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
1544  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
1545  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
1546  * OF THE POSSIBILITY OF SUCH DAMAGE.
1547  */