r20180: Ensure that pam returns the correct error messages
[sfrench/samba-autobuild/.git] / source / 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         /* parse arguments */
1058         int ctrl = _pam_parse(pamh, flags, argc, argv, NULL);
1059         if (ctrl == -1) {
1060                 return PAM_SYSTEM_ERR;
1061         }
1062
1063         _pam_log_debug(pamh, ctrl, LOG_DEBUG, "pam_winbind: pam_sm_setcred (flags: 0x%04x)", flags);
1064
1065         if (flags & PAM_DELETE_CRED) {
1066                 return pam_sm_close_session(pamh, flags, argc, argv);
1067         }
1068
1069         return PAM_SUCCESS;
1070 }
1071
1072 /*
1073  * Account management. We want to verify that the account exists 
1074  * before returning PAM_SUCCESS
1075  */
1076 PAM_EXTERN
1077 int pam_sm_acct_mgmt(pam_handle_t *pamh, int flags,
1078                    int argc, const char **argv)
1079 {
1080         const char *username;
1081         int retval = PAM_USER_UNKNOWN;
1082         void *tmp = NULL;
1083
1084         /* parse arguments */
1085         int ctrl = _pam_parse(pamh, flags, argc, argv, NULL);
1086         if (ctrl == -1) {
1087                 return PAM_SYSTEM_ERR;
1088         }
1089
1090         _pam_log_debug(pamh, ctrl, LOG_DEBUG, "pam_winbind: pam_sm_acct_mgmt (flags: 0x%04x)", flags);
1091
1092
1093         /* Get the username */
1094         retval = pam_get_user(pamh, &username, NULL);
1095         if ((retval != PAM_SUCCESS) || (!username)) {
1096                 _pam_log_debug(pamh, ctrl, LOG_DEBUG,"can not get the username");
1097                 return PAM_SERVICE_ERR;
1098         }
1099
1100         /* Verify the username */
1101         retval = valid_user(pamh, ctrl, username);
1102         switch (retval) {
1103         case -1:
1104                 /* some sort of system error. The log was already printed */
1105                 return PAM_SERVICE_ERR;
1106         case 1:
1107                 /* the user does not exist */
1108                 _pam_log_debug(pamh, ctrl, LOG_NOTICE, "user '%s' not found", username);
1109                 if (ctrl & WINBIND_UNKNOWN_OK_ARG) {
1110                         return PAM_IGNORE;
1111                 }
1112                 return PAM_USER_UNKNOWN;
1113         case 0:
1114                 pam_get_data( pamh, PAM_WINBIND_NEW_AUTHTOK_REQD, (const void **)&tmp);
1115                 if (tmp != NULL) {
1116                         retval = atoi((const char *)tmp);
1117                         switch (retval) {
1118                         case PAM_AUTHTOK_EXPIRED:
1119                                 /* fall through, since new token is required in this case */
1120                         case PAM_NEW_AUTHTOK_REQD:
1121                                 _pam_log(pamh, ctrl, LOG_WARNING, "pam_sm_acct_mgmt success but %s is set", 
1122                                          PAM_WINBIND_NEW_AUTHTOK_REQD);
1123                                 _pam_log(pamh, ctrl, LOG_NOTICE, "user '%s' needs new password", username);
1124                                 /* PAM_AUTHTOKEN_REQD does not exist, but is documented in the manpage */
1125                                 return PAM_NEW_AUTHTOK_REQD; 
1126                         default:
1127                                 _pam_log(pamh, ctrl, LOG_WARNING, "pam_sm_acct_mgmt success");
1128                                 _pam_log(pamh, ctrl, LOG_NOTICE, "user '%s' granted access", username);
1129                                 return PAM_SUCCESS;
1130                         }
1131                 }
1132
1133                 /* Otherwise, the authentication looked good */
1134                 _pam_log(pamh, ctrl, LOG_NOTICE, "user '%s' granted access", username);
1135                 return PAM_SUCCESS;
1136         default:
1137                 /* we don't know anything about this return value */
1138                 _pam_log(pamh, ctrl, LOG_ERR, "internal module error (retval = %d, user = '%s')", 
1139                          retval, username);
1140                 return PAM_SERVICE_ERR;
1141         }
1142
1143         /* should not be reached */
1144         return PAM_IGNORE;
1145 }
1146
1147 PAM_EXTERN
1148 int pam_sm_open_session(pam_handle_t *pamh, int flags,
1149                         int argc, const char **argv)
1150 {
1151         /* parse arguments */
1152         int ctrl = _pam_parse(pamh, flags, argc, argv, NULL);
1153         if (ctrl == -1) {
1154                 return PAM_SYSTEM_ERR;
1155         }
1156
1157         _pam_log_debug(pamh, ctrl, LOG_DEBUG, "pam_winbind: pam_sm_open_session handler (flags: 0x%04x)", flags);
1158
1159         return PAM_SUCCESS;
1160 }
1161
1162 PAM_EXTERN
1163 int pam_sm_close_session(pam_handle_t *pamh, int flags,
1164                          int argc, const char **argv)
1165 {
1166         dictionary *d = NULL;
1167         int retval = PAM_SUCCESS;
1168
1169         /* parse arguments */
1170         int ctrl = _pam_parse(pamh, flags, argc, argv, &d);
1171         if (ctrl == -1) {
1172                 retval = PAM_SYSTEM_ERR;
1173                 goto out;
1174         }
1175
1176         _pam_log_debug(pamh, ctrl, LOG_DEBUG, "pam_winbind: pam_sm_close_session handler (flags: 0x%04x)", flags);
1177
1178         if (!(flags & PAM_DELETE_CRED)) {
1179                 retval = PAM_SUCCESS;
1180                 goto out;
1181         }
1182
1183         if (ctrl & WINBIND_KRB5_AUTH) {
1184
1185                 /* destroy the ccache here */
1186                 struct winbindd_request request;
1187                 struct winbindd_response response;
1188                 const char *user;
1189                 const char *ccname = NULL;
1190                 struct passwd *pwd = NULL;
1191
1192                 ZERO_STRUCT(request);
1193                 ZERO_STRUCT(response);
1194
1195                 retval = pam_get_user(pamh, &user, "Username: ");
1196                 if (retval == PAM_SUCCESS) {
1197                         if (user == NULL) {
1198                                 _pam_log(pamh, ctrl, LOG_ERR, "username was NULL!");
1199                                 retval = PAM_USER_UNKNOWN;
1200                                 goto out;
1201                         }
1202                         if (retval == PAM_SUCCESS) {
1203                                 _pam_log_debug(pamh, ctrl, LOG_DEBUG, "username [%s] obtained", user);
1204                         }
1205                 } else {
1206                         _pam_log_debug(pamh, ctrl, LOG_DEBUG, "could not identify user");
1207                         goto out;
1208                 }
1209
1210                 ccname = pam_getenv(pamh, "KRB5CCNAME");
1211                 if (ccname == NULL) {
1212                         _pam_log_debug(pamh, ctrl, LOG_DEBUG, "user has no KRB5CCNAME environment");
1213                 }
1214
1215                 strncpy(request.data.logoff.user, user,
1216                         sizeof(request.data.logoff.user) - 1);
1217
1218                 if (ccname) {
1219                         strncpy(request.data.logoff.krb5ccname, ccname,
1220                                 sizeof(request.data.logoff.krb5ccname) - 1);
1221                 }
1222
1223                 pwd = getpwnam(user);
1224                 if (pwd == NULL) {
1225                         retval = PAM_USER_UNKNOWN;
1226                         goto out;
1227                 }
1228                 request.data.logoff.uid = pwd->pw_uid;
1229
1230                 request.flags = WBFLAG_PAM_KRB5 | WBFLAG_PAM_CONTACT_TRUSTDOM;
1231
1232                 retval = pam_winbind_request_log(pamh, ctrl, WINBINDD_PAM_LOGOFF, &request, &response, user);
1233         }
1234
1235 out:
1236         if (d) {
1237                 iniparser_freedict(d);
1238         }
1239         return retval;
1240 }
1241
1242
1243
1244 PAM_EXTERN 
1245 int pam_sm_chauthtok(pam_handle_t * pamh, int flags,
1246                      int argc, const char **argv)
1247 {
1248         unsigned int lctrl;
1249         int ret;
1250         unsigned int ctrl;
1251
1252         /* <DO NOT free() THESE> */
1253         const char *user;
1254         char *pass_old, *pass_new;
1255         /* </DO NOT free() THESE> */
1256
1257         char *Announce;
1258         
1259         int retry = 0;
1260         dictionary *d = NULL;
1261
1262         ctrl = _pam_parse(pamh, flags, argc, argv, &d);
1263         if (ctrl == -1) {
1264                 ret = PAM_SYSTEM_ERR;
1265                 goto out;
1266         }
1267
1268         _pam_log_debug(pamh, ctrl, LOG_DEBUG, "pam_winbind: pam_sm_chauthtok (flags: 0x%04x)", flags);
1269
1270         /* clearing offline bit for the auth in the password change */
1271         ctrl &= ~WINBIND_CACHED_LOGIN;
1272
1273         /*
1274          * First get the name of a user
1275          */
1276         ret = pam_get_user(pamh, &user, "Username: ");
1277         if (ret == PAM_SUCCESS) {
1278                 if (user == NULL) {
1279                         _pam_log(pamh, ctrl, LOG_ERR, "username was NULL!");
1280                         ret = PAM_USER_UNKNOWN;
1281                         goto out;
1282                 }
1283                 if (ret == PAM_SUCCESS) {
1284                         _pam_log_debug(pamh, ctrl, LOG_DEBUG, "username [%s] obtained",
1285                                  user);
1286                 }
1287         } else {
1288                 _pam_log_debug(pamh, ctrl, LOG_DEBUG,
1289                          "password - could not identify user");
1290                 goto out;
1291         }
1292
1293         /* check if this is really a user in winbindd, not only in NSS */
1294         ret = valid_user(pamh, ctrl, user);
1295         switch (ret) {
1296                 case 1:
1297                         ret = PAM_USER_UNKNOWN;
1298                         goto out;
1299                 case -1:
1300                         ret = PAM_SYSTEM_ERR;
1301                         goto out;
1302                 default:
1303                         break;
1304         }
1305                 
1306         /*
1307          * obtain and verify the current password (OLDAUTHTOK) for
1308          * the user.
1309          */
1310
1311         if (flags & PAM_PRELIM_CHECK) {
1312                 struct winbindd_response response;
1313                 time_t pwdlastset_prelim = 0;
1314                 
1315                 /* instruct user what is happening */
1316 #define greeting "Changing password for "
1317                 Announce = (char *) malloc(sizeof(greeting) + strlen(user));
1318                 if (Announce == NULL) {
1319                         _pam_log(pamh, ctrl, LOG_CRIT, "password - out of memory");
1320                         ret = PAM_BUF_ERR;
1321                         goto out;
1322                 }
1323                 (void) strcpy(Announce, greeting);
1324                 (void) strcpy(Announce + sizeof(greeting) - 1, user);
1325 #undef greeting
1326                 
1327                 lctrl = ctrl | WINBIND__OLD_PASSWORD;
1328                 ret = _winbind_read_password(pamh, lctrl,
1329                                                 Announce,
1330                                                 "(current) NT password: ",
1331                                                 NULL,
1332                                                 (const char **) &pass_old);
1333                 if (ret != PAM_SUCCESS) {
1334                         _pam_log(pamh, ctrl, LOG_NOTICE, "password - (old) token not obtained");
1335                         goto out;
1336                 }
1337
1338                 /* We don't need krb5 env set for password change test. */
1339                 ctrl &= ~WINBIND_KRB5_AUTH;
1340
1341                 /* verify that this is the password for this user */
1342                 
1343                 ret = winbind_auth_request(pamh, ctrl, user, pass_old,
1344                                         NULL, NULL, &response, &pwdlastset_prelim, NULL);
1345
1346                 if (ret != PAM_ACCT_EXPIRED && 
1347                     ret != PAM_AUTHTOK_EXPIRED &&
1348                     ret != PAM_NEW_AUTHTOK_REQD &&
1349                     ret != PAM_SUCCESS) {
1350                         pass_old = NULL;
1351                         if (d) {
1352                                 iniparser_freedict(d);
1353                         }
1354                         /* Deal with offline errors. */
1355                         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh,
1356                                                 response,
1357                                                 "NT_STATUS_NO_LOGON_SERVERS");
1358                         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh,
1359                                                 response,
1360                                                 "NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND");
1361                         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh,
1362                                                 response,
1363                                                 "NT_STATUS_ACCESS_DENIED");
1364                         return ret;
1365                 }
1366                 
1367                 pam_set_data(pamh, PAM_WINBIND_PWD_LAST_SET, (void *)pwdlastset_prelim, NULL);
1368
1369                 ret = pam_set_item(pamh, PAM_OLDAUTHTOK, (const void *) pass_old);
1370                 pass_old = NULL;
1371                 if (ret != PAM_SUCCESS) {
1372                         _pam_log(pamh, ctrl, LOG_CRIT, "failed to set PAM_OLDAUTHTOK");
1373                 }
1374         } else if (flags & PAM_UPDATE_AUTHTOK) {
1375         
1376                 time_t pwdlastset_update = 0;
1377                 
1378                 /*
1379                  * obtain the proposed password
1380                  */
1381                 
1382                 /*
1383                  * get the old token back. 
1384                  */
1385                 
1386                 ret = _pam_get_item(pamh, PAM_OLDAUTHTOK, &pass_old);
1387                 
1388                 if (ret != PAM_SUCCESS) {
1389                         _pam_log(pamh, ctrl, LOG_NOTICE, "user not authenticated");
1390                         goto out;
1391                 }
1392                 
1393                 lctrl = ctrl;
1394                 
1395                 if (on(WINBIND_USE_AUTHTOK_ARG, lctrl)) {
1396                         lctrl |= WINBIND_USE_FIRST_PASS_ARG;
1397                 }
1398                 retry = 0;
1399                 ret = PAM_AUTHTOK_ERR;
1400                 while ((ret != PAM_SUCCESS) && (retry++ < MAX_PASSWD_TRIES)) {
1401                         /*
1402                          * use_authtok is to force the use of a previously entered
1403                          * password -- needed for pluggable password strength checking
1404                          */
1405                         
1406                         ret = _winbind_read_password(pamh, lctrl,
1407                                                         NULL,
1408                                                         "Enter new NT password: ",
1409                                                         "Retype new NT password: ",
1410                                                         (const char **) &pass_new);
1411                         
1412                         if (ret != PAM_SUCCESS) {
1413                                 _pam_log_debug(pamh, ctrl, LOG_ALERT
1414                                          ,"password - new password not obtained");
1415                                 pass_old = NULL;/* tidy up */
1416                                 goto out;
1417                         }
1418
1419                         /*
1420                          * At this point we know who the user is and what they
1421                          * propose as their new password. Verify that the new
1422                          * password is acceptable.
1423                          */
1424                         
1425                         if (pass_new[0] == '\0') {/* "\0" password = NULL */
1426                                 pass_new = NULL;
1427                         }
1428                 }
1429                 
1430                 /*
1431                  * By reaching here we have approved the passwords and must now
1432                  * rebuild the password database file.
1433                  */
1434                 _pam_get_data( pamh, PAM_WINBIND_PWD_LAST_SET,
1435                                &pwdlastset_update);
1436
1437                 ret = winbind_chauthtok_request(pamh, ctrl, user, pass_old, pass_new, pwdlastset_update);
1438                 if (ret) {
1439                         _pam_overwrite(pass_new);
1440                         _pam_overwrite(pass_old);
1441                         pass_old = pass_new = NULL;
1442                         goto out;
1443                 }
1444
1445                 /* just in case we need krb5 creds after a password change over msrpc */
1446
1447                 if (ctrl & WINBIND_KRB5_AUTH) {
1448                         struct winbindd_response response;
1449
1450                         const char *member = get_member_from_config(pamh, argc, argv, ctrl, d);
1451                         const char *cctype = get_krb5_cc_type_from_config(pamh, argc, argv, ctrl, d);
1452
1453                         ret = winbind_auth_request(pamh, ctrl, user, pass_new,
1454                                                         member, cctype, &response, NULL, NULL);
1455                         _pam_overwrite(pass_new);
1456                         _pam_overwrite(pass_old);
1457                         pass_old = pass_new = NULL;
1458                         if (d) {
1459                                 iniparser_freedict(d);
1460                         }
1461                         /* Deal with offline errors. */
1462                         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh,
1463                                                 response,
1464                                                 "NT_STATUS_NO_LOGON_SERVERS");
1465                         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh,
1466                                                 response,
1467                                                 "NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND");
1468                         PAM_WB_REMARK_CHECK_RESPONSE_RET(pamh,
1469                                                 response,
1470                                                 "NT_STATUS_ACCESS_DENIED");
1471                         return ret;
1472                 }
1473         } else {
1474                 ret = PAM_SERVICE_ERR;
1475         }
1476
1477 out:
1478         if (d) {
1479                 iniparser_freedict(d);
1480         }
1481         return ret;
1482 }
1483
1484 #ifdef PAM_STATIC
1485
1486 /* static module data */
1487
1488 struct pam_module _pam_winbind_modstruct = {
1489         MODULE_NAME,
1490         pam_sm_authenticate,
1491         pam_sm_setcred,
1492         pam_sm_acct_mgmt,
1493         pam_sm_open_session,
1494         pam_sm_close_session,
1495         pam_sm_chauthtok
1496 };
1497
1498 #endif
1499
1500 /*
1501  * Copyright (c) Andrew Tridgell  <tridge@samba.org>   2000
1502  * Copyright (c) Tim Potter       <tpot@samba.org>     2000
1503  * Copyright (c) Andrew Bartlettt <abartlet@samba.org> 2002
1504  * Copyright (c) Guenther Deschner <gd@samba.org>      2005-2006
1505  * Copyright (c) Jan Rêkorajski 1999.
1506  * Copyright (c) Andrew G. Morgan 1996-8.
1507  * Copyright (c) Alex O. Yuriev, 1996.
1508  * Copyright (c) Cristian Gafton 1996.
1509  * Copyright (C) Elliot Lee <sopwith@redhat.com> 1996, Red Hat Software. 
1510  *
1511  * Redistribution and use in source and binary forms, with or without
1512  * modification, are permitted provided that the following conditions
1513  * are met:
1514  * 1. Redistributions of source code must retain the above copyright
1515  *    notice, and the entire permission notice in its entirety,
1516  *    including the disclaimer of warranties.
1517  * 2. Redistributions in binary form must reproduce the above copyright
1518  *    notice, this list of conditions and the following disclaimer in the
1519  *    documentation and/or other materials provided with the distribution.
1520  * 3. The name of the author may not be used to endorse or promote
1521  *    products derived from this software without specific prior
1522  *    written permission.
1523  *
1524  * ALTERNATIVELY, this product may be distributed under the terms of
1525  * the GNU Public License, in which case the provisions of the GPL are
1526  * required INSTEAD OF the above restrictions.  (This clause is
1527  * necessary due to a potential bad interaction between the GPL and
1528  * the restrictions contained in a BSD-style copyright.)
1529  *
1530  * THIS SOFTWARE IS PROVIDED `AS IS'' AND ANY EXPRESS OR IMPLIED
1531  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
1532  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
1533  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
1534  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
1535  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
1536  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
1537  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
1538  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
1539  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
1540  * OF THE POSSIBILITY OF SUCH DAMAGE.
1541  */