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