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