pam_winbind: remove unused pam_winbind_request().
[kai/samba.git] / source3 / nsswitch / pam_winbind.c
1 /* pam_winbind module
2
3    Copyright Andrew Tridgell <tridge@samba.org> 2000
4    Copyright Tim Potter <tpot@samba.org> 2000
5    Copyright Andrew Bartlett <abartlet@samba.org> 2002
6    Copyright Guenther Deschner <gd@samba.org> 2005-2008
7
8    largely based on pam_userdb by Cristian Gafton <gafton@redhat.com> also
9    contains large slabs of code from pam_unix by Elliot Lee
10    <sopwith@redhat.com> (see copyright below for full details)
11 */
12
13 #include "pam_winbind.h"
14
15 static int wbc_error_to_pam_error(wbcErr status)
16 {
17         switch (status) {
18                 case WBC_ERR_SUCCESS:
19                         return PAM_SUCCESS;
20                 case WBC_ERR_NOT_IMPLEMENTED:
21                         return PAM_SERVICE_ERR;
22                 case WBC_ERR_UNKNOWN_FAILURE:
23                         break;
24                 case WBC_ERR_NO_MEMORY:
25                         return PAM_BUF_ERR;
26                 case WBC_ERR_INVALID_SID:
27                 case WBC_ERR_INVALID_PARAM:
28                         break;
29                 case WBC_ERR_WINBIND_NOT_AVAILABLE:
30                         return PAM_AUTHINFO_UNAVAIL;
31                 case WBC_ERR_DOMAIN_NOT_FOUND:
32                         return PAM_AUTHINFO_UNAVAIL;
33                 case WBC_ERR_INVALID_RESPONSE:
34                         return PAM_BUF_ERR;
35                 case WBC_ERR_NSS_ERROR:
36                         return PAM_USER_UNKNOWN;
37                 case WBC_ERR_AUTH_ERROR:
38                         return PAM_AUTH_ERR;
39                 case WBC_ERR_UNKNOWN_USER:
40                         return PAM_USER_UNKNOWN;
41                 case WBC_ERR_UNKNOWN_GROUP:
42                         return PAM_USER_UNKNOWN;
43                 case WBC_ERR_PWD_CHANGE_FAILED:
44                         break;
45         }
46
47         /* be paranoid */
48         return PAM_AUTH_ERR;
49 }
50
51 static const char *_pam_error_code_str(int err)
52 {
53         switch (err) {
54                 case PAM_SUCCESS:
55                         return "PAM_SUCCESS";
56                 case PAM_OPEN_ERR:
57                         return "PAM_OPEN_ERR";
58                 case PAM_SYMBOL_ERR:
59                         return "PAM_SYMBOL_ERR";
60                 case PAM_SERVICE_ERR:
61                         return "PAM_SERVICE_ERR";
62                 case PAM_SYSTEM_ERR:
63                         return "PAM_SYSTEM_ERR";
64                 case PAM_BUF_ERR:
65                         return "PAM_BUF_ERR";
66                 case PAM_PERM_DENIED:
67                         return "PAM_PERM_DENIED";
68                 case PAM_AUTH_ERR:
69                         return "PAM_AUTH_ERR";
70                 case PAM_CRED_INSUFFICIENT:
71                         return "PAM_CRED_INSUFFICIENT";
72                 case PAM_AUTHINFO_UNAVAIL:
73                         return "PAM_AUTHINFO_UNAVAIL";
74                 case PAM_USER_UNKNOWN:
75                         return "PAM_USER_UNKNOWN";
76                 case PAM_MAXTRIES:
77                         return "PAM_MAXTRIES";
78                 case PAM_NEW_AUTHTOK_REQD:
79                         return "PAM_NEW_AUTHTOK_REQD";
80                 case PAM_ACCT_EXPIRED:
81                         return "PAM_ACCT_EXPIRED";
82                 case PAM_SESSION_ERR:
83                         return "PAM_SESSION_ERR";
84                 case PAM_CRED_UNAVAIL:
85                         return "PAM_CRED_UNAVAIL";
86                 case PAM_CRED_EXPIRED:
87                         return "PAM_CRED_EXPIRED";
88                 case PAM_CRED_ERR:
89                         return "PAM_CRED_ERR";
90                 case PAM_NO_MODULE_DATA:
91                         return "PAM_NO_MODULE_DATA";
92                 case PAM_CONV_ERR:
93                         return "PAM_CONV_ERR";
94                 case PAM_AUTHTOK_ERR:
95                         return "PAM_AUTHTOK_ERR";
96                 case PAM_AUTHTOK_RECOVERY_ERR:
97                         return "PAM_AUTHTOK_RECOVERY_ERR";
98                 case PAM_AUTHTOK_LOCK_BUSY:
99                         return "PAM_AUTHTOK_LOCK_BUSY";
100                 case PAM_AUTHTOK_DISABLE_AGING:
101                         return "PAM_AUTHTOK_DISABLE_AGING";
102                 case PAM_TRY_AGAIN:
103                         return "PAM_TRY_AGAIN";
104                 case PAM_IGNORE:
105                         return "PAM_IGNORE";
106                 case PAM_ABORT:
107                         return "PAM_ABORT";
108                 case PAM_AUTHTOK_EXPIRED:
109                         return "PAM_AUTHTOK_EXPIRED";
110 #ifdef PAM_MODULE_UNKNOWN
111                 case PAM_MODULE_UNKNOWN:
112                         return "PAM_MODULE_UNKNOWN";
113 #endif
114 #ifdef PAM_BAD_ITEM
115                 case PAM_BAD_ITEM:
116                         return "PAM_BAD_ITEM";
117 #endif
118 #ifdef PAM_CONV_AGAIN
119                 case PAM_CONV_AGAIN:
120                         return "PAM_CONV_AGAIN";
121 #endif
122 #ifdef PAM_INCOMPLETE
123                 case PAM_INCOMPLETE:
124                         return "PAM_INCOMPLETE";
125 #endif
126                 default:
127                         return NULL;
128         }
129 }
130
131 #define _PAM_LOG_FUNCTION_ENTER(function, ctx) \
132         do { \
133                 _pam_log_debug(ctx, LOG_DEBUG, "[pamh: %p] ENTER: " \
134                                function " (flags: 0x%04x)", ctx->pamh, ctx->flags); \
135                 _pam_log_state(ctx); \
136         } while (0)
137
138 #define _PAM_LOG_FUNCTION_LEAVE(function, ctx, retval) \
139         do { \
140                 _pam_log_debug(ctx, LOG_DEBUG, "[pamh: %p] LEAVE: " \
141                                function " returning %d (%s)", ctx->pamh, retval, \
142                                _pam_error_code_str(retval)); \
143                 _pam_log_state(ctx); \
144         } while (0)
145
146 /* data tokens */
147
148 #define MAX_PASSWD_TRIES        3
149
150 /*
151  * Work around the pam API that has functions with void ** as parameters
152  * These lead to strict aliasing warnings with gcc.
153  */
154 static int _pam_get_item(const pam_handle_t *pamh,
155                          int item_type,
156                          const void *_item)
157 {
158         const void **item = (const void **)_item;
159         return pam_get_item(pamh, item_type, item);
160 }
161 static int _pam_get_data(const pam_handle_t *pamh,
162                          const char *module_data_name,
163                          const void *_data)
164 {
165         const void **data = (const void **)_data;
166         return pam_get_data(pamh, module_data_name, data);
167 }
168
169 /* some syslogging */
170
171 #ifdef HAVE_PAM_VSYSLOG
172 static void _pam_log_int(const pam_handle_t *pamh,
173                          int err,
174                          const char *format,
175                          va_list args)
176 {
177         pam_vsyslog(pamh, err, format, args);
178 }
179 #else
180 static void _pam_log_int(const pam_handle_t *pamh,
181                          int err,
182                          const char *format,
183                          va_list args)
184 {
185         char *format2 = NULL;
186         const char *service;
187
188         _pam_get_item(pamh, PAM_SERVICE, &service);
189
190         format2 = (char *)malloc(strlen(MODULE_NAME)+strlen(format)+strlen(service)+5);
191         if (format2 == NULL) {
192                 /* what else todo ? */
193                 vsyslog(err, format, args);
194                 return;
195         }
196
197         sprintf(format2, "%s(%s): %s", MODULE_NAME, service, format);
198         vsyslog(err, format2, args);
199         SAFE_FREE(format2);
200 }
201 #endif /* HAVE_PAM_VSYSLOG */
202
203 static bool _pam_log_is_silent(int ctrl)
204 {
205         return on(ctrl, WINBIND_SILENT);
206 }
207
208 static void _pam_log(struct pwb_context *r, int err, const char *format, ...) PRINTF_ATTRIBUTE(3,4);
209 static void _pam_log(struct pwb_context *r, int err, const char *format, ...)
210 {
211         va_list args;
212
213         if (_pam_log_is_silent(r->ctrl)) {
214                 return;
215         }
216
217         va_start(args, format);
218         _pam_log_int(r->pamh, err, format, args);
219         va_end(args);
220 }
221 static void __pam_log(const pam_handle_t *pamh, int ctrl, int err, const char *format, ...) PRINTF_ATTRIBUTE(4,5);
222 static void __pam_log(const pam_handle_t *pamh, int ctrl, int err, const char *format, ...)
223 {
224         va_list args;
225
226         if (_pam_log_is_silent(ctrl)) {
227                 return;
228         }
229
230         va_start(args, format);
231         _pam_log_int(pamh, err, format, args);
232         va_end(args);
233 }
234
235 static bool _pam_log_is_debug_enabled(int ctrl)
236 {
237         if (ctrl == -1) {
238                 return false;
239         }
240
241         if (_pam_log_is_silent(ctrl)) {
242                 return false;
243         }
244
245         if (!(ctrl & WINBIND_DEBUG_ARG)) {
246                 return false;
247         }
248
249         return true;
250 }
251
252 static bool _pam_log_is_debug_state_enabled(int ctrl)
253 {
254         if (!(ctrl & WINBIND_DEBUG_STATE)) {
255                 return false;
256         }
257
258         return _pam_log_is_debug_enabled(ctrl);
259 }
260
261 static void _pam_log_debug(struct pwb_context *r, int err, const char *format, ...) PRINTF_ATTRIBUTE(3,4);
262 static void _pam_log_debug(struct pwb_context *r, int err, const char *format, ...)
263 {
264         va_list args;
265
266         if (!_pam_log_is_debug_enabled(r->ctrl)) {
267                 return;
268         }
269
270         va_start(args, format);
271         _pam_log_int(r->pamh, err, format, args);
272         va_end(args);
273 }
274 static void __pam_log_debug(const pam_handle_t *pamh, int ctrl, int err, const char *format, ...) PRINTF_ATTRIBUTE(4,5);
275 static void __pam_log_debug(const pam_handle_t *pamh, int ctrl, int err, const char *format, ...)
276 {
277         va_list args;
278
279         if (!_pam_log_is_debug_enabled(ctrl)) {
280                 return;
281         }
282
283         va_start(args, format);
284         _pam_log_int(pamh, err, format, args);
285         va_end(args);
286 }
287
288 static void _pam_log_state_datum(struct pwb_context *ctx,
289                                  int item_type,
290                                  const char *key,
291                                  int is_string)
292 {
293         const void *data = NULL;
294         if (item_type != 0) {
295                 pam_get_item(ctx->pamh, item_type, &data);
296         } else {
297                 pam_get_data(ctx->pamh, key, &data);
298         }
299         if (data != NULL) {
300                 const char *type = (item_type != 0) ? "ITEM" : "DATA";
301                 if (is_string != 0) {
302                         _pam_log_debug(ctx, LOG_DEBUG,
303                                        "[pamh: %p] STATE: %s(%s) = \"%s\" (%p)",
304                                        ctx->pamh, type, key, (const char *)data,
305                                        data);
306                 } else {
307                         _pam_log_debug(ctx, LOG_DEBUG,
308                                        "[pamh: %p] STATE: %s(%s) = %p",
309                                        ctx->pamh, type, key, data);
310                 }
311         }
312 }
313
314 #define _PAM_LOG_STATE_DATA_POINTER(ctx, module_data_name) \
315         _pam_log_state_datum(ctx, 0, module_data_name, 0)
316
317 #define _PAM_LOG_STATE_DATA_STRING(ctx, module_data_name) \
318         _pam_log_state_datum(ctx, 0, module_data_name, 1)
319
320 #define _PAM_LOG_STATE_ITEM_POINTER(ctx, item_type) \
321         _pam_log_state_datum(ctx, item_type, #item_type, 0)
322
323 #define _PAM_LOG_STATE_ITEM_STRING(ctx, item_type) \
324         _pam_log_state_datum(ctx, item_type, #item_type, 1)
325
326 #ifdef DEBUG_PASSWORD
327 #define _LOG_PASSWORD_AS_STRING 1
328 #else
329 #define _LOG_PASSWORD_AS_STRING 0
330 #endif
331
332 #define _PAM_LOG_STATE_ITEM_PASSWORD(ctx, item_type) \
333         _pam_log_state_datum(ctx, item_type, #item_type, \
334                              _LOG_PASSWORD_AS_STRING)
335
336 static void _pam_log_state(struct pwb_context *ctx)
337 {
338         if (!_pam_log_is_debug_state_enabled(ctx->ctrl)) {
339                 return;
340         }
341
342         _PAM_LOG_STATE_ITEM_STRING(ctx, PAM_SERVICE);
343         _PAM_LOG_STATE_ITEM_STRING(ctx, PAM_USER);
344         _PAM_LOG_STATE_ITEM_STRING(ctx, PAM_TTY);
345         _PAM_LOG_STATE_ITEM_STRING(ctx, PAM_RHOST);
346         _PAM_LOG_STATE_ITEM_STRING(ctx, PAM_RUSER);
347         _PAM_LOG_STATE_ITEM_PASSWORD(ctx, PAM_OLDAUTHTOK);
348         _PAM_LOG_STATE_ITEM_PASSWORD(ctx, PAM_AUTHTOK);
349         _PAM_LOG_STATE_ITEM_STRING(ctx, PAM_USER_PROMPT);
350         _PAM_LOG_STATE_ITEM_POINTER(ctx, PAM_CONV);
351 #ifdef PAM_FAIL_DELAY
352         _PAM_LOG_STATE_ITEM_POINTER(ctx, PAM_FAIL_DELAY);
353 #endif
354 #ifdef PAM_REPOSITORY
355         _PAM_LOG_STATE_ITEM_POINTER(ctx, PAM_REPOSITORY);
356 #endif
357
358         _PAM_LOG_STATE_DATA_STRING(ctx, PAM_WINBIND_HOMEDIR);
359         _PAM_LOG_STATE_DATA_STRING(ctx, PAM_WINBIND_LOGONSCRIPT);
360         _PAM_LOG_STATE_DATA_STRING(ctx, PAM_WINBIND_LOGONSERVER);
361         _PAM_LOG_STATE_DATA_STRING(ctx, PAM_WINBIND_PROFILEPATH);
362         _PAM_LOG_STATE_DATA_STRING(ctx,
363                                    PAM_WINBIND_NEW_AUTHTOK_REQD);
364                                    /* Use atoi to get PAM result code */
365         _PAM_LOG_STATE_DATA_STRING(ctx,
366                                    PAM_WINBIND_NEW_AUTHTOK_REQD_DURING_AUTH);
367         _PAM_LOG_STATE_DATA_POINTER(ctx, PAM_WINBIND_PWD_LAST_SET);
368 }
369
370 static int _pam_parse(const pam_handle_t *pamh,
371                       int flags,
372                       int argc,
373                       const char **argv,
374                       dictionary **result_d)
375 {
376         int ctrl = 0;
377         const char *config_file = NULL;
378         int i;
379         const char **v;
380         dictionary *d = NULL;
381
382         if (flags & PAM_SILENT) {
383                 ctrl |= WINBIND_SILENT;
384         }
385
386         for (i=argc,v=argv; i-- > 0; ++v) {
387                 if (!strncasecmp(*v, "config", strlen("config"))) {
388                         ctrl |= WINBIND_CONFIG_FILE;
389                         config_file = v[i];
390                         break;
391                 }
392         }
393
394         if (config_file == NULL) {
395                 config_file = PAM_WINBIND_CONFIG_FILE;
396         }
397
398         d = iniparser_load(config_file);
399         if (d == NULL) {
400                 goto config_from_pam;
401         }
402
403         if (iniparser_getboolean(d, "global:debug", false)) {
404                 ctrl |= WINBIND_DEBUG_ARG;
405         }
406
407         if (iniparser_getboolean(d, "global:debug_state", false)) {
408                 ctrl |= WINBIND_DEBUG_STATE;
409         }
410
411         if (iniparser_getboolean(d, "global:cached_login", false)) {
412                 ctrl |= WINBIND_CACHED_LOGIN;
413         }
414
415         if (iniparser_getboolean(d, "global:krb5_auth", false)) {
416                 ctrl |= WINBIND_KRB5_AUTH;
417         }
418
419         if (iniparser_getboolean(d, "global:silent", false)) {
420                 ctrl |= WINBIND_SILENT;
421         }
422
423         if (iniparser_getstr(d, "global:krb5_ccache_type") != NULL) {
424                 ctrl |= WINBIND_KRB5_CCACHE_TYPE;
425         }
426
427         if ((iniparser_getstr(d, "global:require-membership-of") != NULL) ||
428             (iniparser_getstr(d, "global:require_membership_of") != NULL)) {
429                 ctrl |= WINBIND_REQUIRED_MEMBERSHIP;
430         }
431
432         if (iniparser_getboolean(d, "global:try_first_pass", false)) {
433                 ctrl |= WINBIND_TRY_FIRST_PASS_ARG;
434         }
435
436         if (iniparser_getint(d, "global:warn_pwd_expire", 0)) {
437                 ctrl |= WINBIND_WARN_PWD_EXPIRE;
438         }
439
440 config_from_pam:
441         /* step through arguments */
442         for (i=argc,v=argv; i-- > 0; ++v) {
443
444                 /* generic options */
445                 if (!strcmp(*v,"debug"))
446                         ctrl |= WINBIND_DEBUG_ARG;
447                 else if (!strcasecmp(*v, "debug_state"))
448                         ctrl |= WINBIND_DEBUG_STATE;
449                 else if (!strcasecmp(*v, "silent"))
450                         ctrl |= WINBIND_SILENT;
451                 else if (!strcasecmp(*v, "use_authtok"))
452                         ctrl |= WINBIND_USE_AUTHTOK_ARG;
453                 else if (!strcasecmp(*v, "use_first_pass"))
454                         ctrl |= WINBIND_USE_FIRST_PASS_ARG;
455                 else if (!strcasecmp(*v, "try_first_pass"))
456                         ctrl |= WINBIND_TRY_FIRST_PASS_ARG;
457                 else if (!strcasecmp(*v, "unknown_ok"))
458                         ctrl |= WINBIND_UNKNOWN_OK_ARG;
459                 else if (!strncasecmp(*v, "require_membership_of",
460                                       strlen("require_membership_of")))
461                         ctrl |= WINBIND_REQUIRED_MEMBERSHIP;
462                 else if (!strncasecmp(*v, "require-membership-of",
463                                       strlen("require-membership-of")))
464                         ctrl |= WINBIND_REQUIRED_MEMBERSHIP;
465                 else if (!strcasecmp(*v, "krb5_auth"))
466                         ctrl |= WINBIND_KRB5_AUTH;
467                 else if (!strncasecmp(*v, "krb5_ccache_type",
468                                       strlen("krb5_ccache_type")))
469                         ctrl |= WINBIND_KRB5_CCACHE_TYPE;
470                 else if (!strcasecmp(*v, "cached_login"))
471                         ctrl |= WINBIND_CACHED_LOGIN;
472                 else {
473                         __pam_log(pamh, ctrl, LOG_ERR,
474                                  "pam_parse: unknown option: %s", *v);
475                         return -1;
476                 }
477
478         }
479
480         if (result_d) {
481                 *result_d = d;
482         } else {
483                 if (d) {
484                         iniparser_freedict(d);
485                 }
486         }
487
488         return ctrl;
489 };
490
491 static int _pam_winbind_free_context(struct pwb_context *ctx)
492 {
493         if (!ctx) {
494                 return 0;
495         }
496
497         if (ctx->dict) {
498                 iniparser_freedict(ctx->dict);
499         }
500
501         return 0;
502 }
503
504 static int _pam_winbind_init_context(pam_handle_t *pamh,
505                                      int flags,
506                                      int argc,
507                                      const char **argv,
508                                      struct pwb_context **ctx_p)
509 {
510         struct pwb_context *r = NULL;
511
512         r = TALLOC_ZERO_P(NULL, struct pwb_context);
513         if (!r) {
514                 return PAM_BUF_ERR;
515         }
516
517         talloc_set_destructor(r, _pam_winbind_free_context);
518
519         r->pamh = pamh;
520         r->flags = flags;
521         r->argc = argc;
522         r->argv = argv;
523         r->ctrl = _pam_parse(pamh, flags, argc, argv, &r->dict);
524         if (r->ctrl == -1) {
525                 TALLOC_FREE(r);
526                 return PAM_SYSTEM_ERR;
527         }
528
529         *ctx_p = r;
530
531         return PAM_SUCCESS;
532 }
533
534 static void _pam_winbind_cleanup_func(pam_handle_t *pamh,
535                                       void *data,
536                                       int error_status)
537 {
538         int ctrl = _pam_parse(pamh, 0, 0, NULL, NULL);
539         if (_pam_log_is_debug_state_enabled(ctrl)) {
540                 __pam_log_debug(pamh, ctrl, LOG_DEBUG,
541                                "[pamh: %p] CLEAN: cleaning up PAM data %p "
542                                "(error_status = %d)", pamh, data,
543                                error_status);
544         }
545         TALLOC_FREE(data);
546 }
547
548
549 static const struct ntstatus_errors {
550         const char *ntstatus_string;
551         const char *error_string;
552 } ntstatus_errors[] = {
553         {"NT_STATUS_OK",
554                 "Success"},
555         {"NT_STATUS_BACKUP_CONTROLLER",
556                 "No primary Domain Controler available"},
557         {"NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND",
558                 "No domain controllers found"},
559         {"NT_STATUS_NO_LOGON_SERVERS",
560                 "No logon servers"},
561         {"NT_STATUS_PWD_TOO_SHORT",
562                 "Password too short"},
563         {"NT_STATUS_PWD_TOO_RECENT",
564                 "The password of this user is too recent to change"},
565         {"NT_STATUS_PWD_HISTORY_CONFLICT",
566                 "Password is already in password history"},
567         {"NT_STATUS_PASSWORD_EXPIRED",
568                 "Your password has expired"},
569         {"NT_STATUS_PASSWORD_MUST_CHANGE",
570                 "You need to change your password now"},
571         {"NT_STATUS_INVALID_WORKSTATION",
572                 "You are not allowed to logon from this workstation"},
573         {"NT_STATUS_INVALID_LOGON_HOURS",
574                 "You are not allowed to logon at this time"},
575         {"NT_STATUS_ACCOUNT_EXPIRED",
576                 "Your account has expired. "
577                 "Please contact your System administrator"}, /* SCNR */
578         {"NT_STATUS_ACCOUNT_DISABLED",
579                 "Your account is disabled. "
580                 "Please contact your System administrator"}, /* SCNR */
581         {"NT_STATUS_ACCOUNT_LOCKED_OUT",
582                 "Your account has been locked. "
583                 "Please contact your System administrator"}, /* SCNR */
584         {"NT_STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT",
585                 "Invalid Trust Account"},
586         {"NT_STATUS_NOLOGON_SERVER_TRUST_ACCOUNT",
587                 "Invalid Trust Account"},
588         {"NT_STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT",
589                 "Invalid Trust Account"},
590         {"NT_STATUS_ACCESS_DENIED",
591                 "Access is denied"},
592         {NULL, NULL}
593 };
594
595 static const char *_get_ntstatus_error_string(const char *nt_status_string)
596 {
597         int i;
598         for (i=0; ntstatus_errors[i].ntstatus_string != NULL; i++) {
599                 if (!strcasecmp(ntstatus_errors[i].ntstatus_string,
600                                 nt_status_string)) {
601                         return ntstatus_errors[i].error_string;
602                 }
603         }
604         return NULL;
605 }
606
607 /* --- authentication management functions --- */
608
609 /* Attempt a conversation */
610
611 static int converse(const pam_handle_t *pamh,
612                     int nargs,
613                     struct pam_message **message,
614                     struct pam_response **response)
615 {
616         int retval;
617         struct pam_conv *conv;
618
619         retval = _pam_get_item(pamh, PAM_CONV, &conv);
620         if (retval == PAM_SUCCESS) {
621                 retval = conv->conv(nargs,
622                                     (const struct pam_message **)message,
623                                     response, conv->appdata_ptr);
624         }
625
626         return retval; /* propagate error status */
627 }
628
629
630 static int _make_remark(struct pwb_context *ctx,
631                         int type,
632                         const char *text)
633 {
634         int retval = PAM_SUCCESS;
635
636         struct pam_message *pmsg[1], msg[1];
637         struct pam_response *resp;
638
639         if (ctx->flags & WINBIND_SILENT) {
640                 return PAM_SUCCESS;
641         }
642
643         pmsg[0] = &msg[0];
644         msg[0].msg = discard_const_p(char, text);
645         msg[0].msg_style = type;
646
647         resp = NULL;
648         retval = converse(ctx->pamh, 1, pmsg, &resp);
649
650         if (resp) {
651                 _pam_drop_reply(resp, 1);
652         }
653         return retval;
654 }
655
656 static int _make_remark_v(struct pwb_context *ctx,
657                           int type,
658                           const char *format,
659                           va_list args)
660 {
661         char *var;
662         int ret;
663
664         ret = vasprintf(&var, format, args);
665         if (ret < 0) {
666                 _pam_log(ctx, LOG_ERR, "memory allocation failure");
667                 return ret;
668         }
669
670         ret = _make_remark(ctx, type, var);
671         SAFE_FREE(var);
672         return ret;
673 }
674
675 static int _make_remark_format(struct pwb_context *ctx, int type, const char *format, ...) PRINTF_ATTRIBUTE(3,4);
676 static int _make_remark_format(struct pwb_context *ctx, int type, const char *format, ...)
677 {
678         int ret;
679         va_list args;
680
681         va_start(args, format);
682         ret = _make_remark_v(ctx, type, format, args);
683         va_end(args);
684         return ret;
685 }
686
687 static int pam_winbind_request_log(struct pwb_context *ctx,
688                                    int retval,
689                                    const char *user,
690                                    const char *fn)
691 {
692         switch (retval) {
693         case PAM_AUTH_ERR:
694                 /* incorrect password */
695                 _pam_log(ctx, LOG_WARNING, "user '%s' denied access "
696                          "(incorrect password or invalid membership)", user);
697                 return retval;
698         case PAM_ACCT_EXPIRED:
699                 /* account expired */
700                 _pam_log(ctx, LOG_WARNING, "user '%s' account expired",
701                          user);
702                 return retval;
703         case PAM_AUTHTOK_EXPIRED:
704                 /* password expired */
705                 _pam_log(ctx, LOG_WARNING, "user '%s' password expired",
706                          user);
707                 return retval;
708         case PAM_NEW_AUTHTOK_REQD:
709                 /* new password required */
710                 _pam_log(ctx, LOG_WARNING, "user '%s' new password "
711                          "required", user);
712                 return retval;
713         case PAM_USER_UNKNOWN:
714                 /* the user does not exist */
715                 _pam_log_debug(ctx, LOG_NOTICE, "user '%s' not found",
716                                user);
717                 if (ctx->ctrl & WINBIND_UNKNOWN_OK_ARG) {
718                         return PAM_IGNORE;
719                 }
720                 return retval;
721         case PAM_SUCCESS:
722                 /* Otherwise, the authentication looked good */
723                 if (strcmp(fn, "wbcLogonUser") == 0) {
724                         _pam_log(ctx, LOG_NOTICE,
725                                  "user '%s' granted access", user);
726                 } else {
727                         _pam_log(ctx, LOG_NOTICE,
728                                  "user '%s' OK", user);
729                 }
730                 return retval;
731         default:
732                 /* we don't know anything about this return value */
733                 _pam_log(ctx, LOG_ERR,
734                          "internal module error (retval = %s(%d), user = '%s')",
735                         _pam_error_code_str(retval), retval, user);
736                 return retval;
737         }
738 }
739
740 static int wbc_auth_error_to_pam_error(struct pwb_context *ctx,
741                                        struct wbcAuthErrorInfo *e,
742                                        wbcErr status,
743                                        const char *username,
744                                        const char *fn)
745 {
746         int ret = PAM_AUTH_ERR;
747
748         if (WBC_ERROR_IS_OK(status)) {
749                 _pam_log_debug(ctx, LOG_DEBUG, "request %s succeeded",
750                         fn);
751                 ret = PAM_SUCCESS;
752                 return pam_winbind_request_log(ctx, ret, username, fn);
753         }
754
755         if (e) {
756                 if (e->pam_error != PAM_SUCCESS) {
757                         _pam_log(ctx, LOG_ERR,
758                                  "request %s failed: %s, "
759                                  "PAM error: %s (%d), NTSTATUS: %s, "
760                                  "Error message was: %s",
761                                  fn,
762                                  wbcErrorString(status),
763                                  _pam_error_code_str(e->pam_error),
764                                  e->pam_error,
765                                  e->nt_string,
766                                  e->display_string);
767                         ret = e->pam_error;
768                         return pam_winbind_request_log(ctx, ret, username, fn);
769                 }
770
771                 _pam_log(ctx, LOG_ERR, "request %s failed, but PAM error 0!", fn);
772
773                 ret = PAM_SERVICE_ERR;
774                 return pam_winbind_request_log(ctx, ret, username, fn);
775         }
776
777         ret = wbc_error_to_pam_error(status);
778         return pam_winbind_request_log(ctx, ret, username, fn);
779 }
780
781
782 /**
783  * send a password expiry message if required
784  *
785  * @param ctx PAM winbind context.
786  * @param next_change expected (calculated) next expiry date.
787  * @param already_expired pointer to a boolean to indicate if the password is
788  *        already expired.
789  *
790  * @return boolean Returns true if message has been sent, false if not.
791  */
792
793 static bool _pam_send_password_expiry_message(struct pwb_context *ctx,
794                                               time_t next_change,
795                                               time_t now,
796                                               int warn_pwd_expire,
797                                               bool *already_expired)
798 {
799         int days = 0;
800         struct tm tm_now, tm_next_change;
801
802         if (already_expired) {
803                 *already_expired = false;
804         }
805
806         if (next_change <= now) {
807                 PAM_WB_REMARK_DIRECT(ctx, "NT_STATUS_PASSWORD_EXPIRED");
808                 if (already_expired) {
809                         *already_expired = true;
810                 }
811                 return true;
812         }
813
814         if ((next_change < 0) ||
815             (next_change > now + warn_pwd_expire * SECONDS_PER_DAY)) {
816                 return false;
817         }
818
819         if ((localtime_r(&now, &tm_now) == NULL) ||
820             (localtime_r(&next_change, &tm_next_change) == NULL)) {
821                 return false;
822         }
823
824         days = (tm_next_change.tm_yday+tm_next_change.tm_year*365) -
825                (tm_now.tm_yday+tm_now.tm_year*365);
826
827         if (days == 0) {
828                 _make_remark(ctx, PAM_TEXT_INFO,
829                              "Your password expires today");
830                 return true;
831         }
832
833         if (days > 0 && days < warn_pwd_expire) {
834                 _make_remark_format(ctx, PAM_TEXT_INFO,
835                                     "Your password will expire in %d %s",
836                                     days, (days > 1) ? "days":"day");
837                 return true;
838         }
839
840         return false;
841 }
842
843 /**
844  * Send a warning if the password expires in the near future
845  *
846  * @param ctx PAM winbind context.
847  * @param response The full authentication response structure.
848  * @param already_expired boolean, is the pwd already expired?
849  *
850  * @return void.
851  */
852
853 static void _pam_warn_password_expiry(struct pwb_context *ctx,
854                                       const struct wbcAuthUserInfo *info,
855                                       const struct wbcUserPasswordPolicyInfo *policy,
856                                       int warn_pwd_expire,
857                                       bool *already_expired)
858 {
859         time_t now = time(NULL);
860         time_t next_change = 0;
861
862         if (!info || !policy) {
863                 return;
864         }
865
866         if (already_expired) {
867                 *already_expired = false;
868         }
869
870         /* accounts with WBC_ACB_PWNOEXP set never receive a warning */
871         if (info->acct_flags & WBC_ACB_PWNOEXP) {
872                 return;
873         }
874
875         /* no point in sending a warning if this is a grace logon */
876         if (PAM_WB_GRACE_LOGON(info->user_flags)) {
877                 return;
878         }
879
880         /* check if the info3 must change timestamp has been set */
881         next_change = info->pass_must_change_time;
882
883         if (_pam_send_password_expiry_message(ctx, next_change, now,
884                                               warn_pwd_expire,
885                                               already_expired)) {
886                 return;
887         }
888
889         /* now check for the global password policy */
890         /* good catch from Ralf Haferkamp: an expiry of "never" is translated
891          * to -1 */
892         if (policy->expire <= 0) {
893                 return;
894         }
895
896         next_change = info->pass_last_set_time + policy->expire;
897
898         if (_pam_send_password_expiry_message(ctx, next_change, now,
899                                               warn_pwd_expire,
900                                               already_expired)) {
901                 return;
902         }
903
904         /* no warning sent */
905 }
906
907 #define IS_SID_STRING(name) (strncmp("S-", name, 2) == 0)
908
909 /**
910  * Append a string, making sure not to overflow and to always return a
911  * NULL-terminated string.
912  *
913  * @param dest Destination string buffer (must already be NULL-terminated).
914  * @param src Source string buffer.
915  * @param dest_buffer_size Size of dest buffer in bytes.
916  *
917  * @return false if dest buffer is not big enough (no bytes copied), true on
918  * success.
919  */
920
921 static bool safe_append_string(char *dest,
922                                const char *src,
923                                int dest_buffer_size)
924 {
925         int dest_length = strlen(dest);
926         int src_length = strlen(src);
927
928         if (dest_length + src_length + 1 > dest_buffer_size) {
929                 return false;
930         }
931
932         memcpy(dest + dest_length, src, src_length + 1);
933         return true;
934 }
935
936 /**
937  * Convert a names into a SID string, appending it to a buffer.
938  *
939  * @param ctx PAM winbind context.
940  * @param user User in PAM request.
941  * @param name Name to convert.
942  * @param sid_list_buffer Where to append the string sid.
943  * @param sid_list_buffer Size of sid_list_buffer (in bytes).
944  *
945  * @return false on failure, true on success.
946  */
947 static bool winbind_name_to_sid_string(struct pwb_context *ctx,
948                                        const char *user,
949                                        const char *name,
950                                        char *sid_list_buffer,
951                                        int sid_list_buffer_size)
952 {
953         const char* sid_string;
954
955         /* lookup name? */
956         if (IS_SID_STRING(name)) {
957                 sid_string = name;
958         } else {
959                 wbcErr wbc_status;
960                 struct wbcDomainSid sid;
961                 enum wbcSidType type;
962                 char *sid_str;
963
964                 _pam_log_debug(ctx, LOG_DEBUG,
965                                "no sid given, looking up: %s\n", name);
966
967                 wbc_status = wbcLookupName("", name, &sid, &type);
968                 if (!WBC_ERROR_IS_OK(wbc_status)) {
969                         _pam_log(ctx, LOG_INFO,
970                                  "could not lookup name: %s\n", name);
971                         return false;
972                 }
973
974                 wbc_status = wbcSidToString(&sid, &sid_str);
975                 if (!WBC_ERROR_IS_OK(wbc_status)) {
976                         return false;
977                 }
978
979                 wbcFreeMemory(sid_str);
980                 sid_string = sid_str;
981         }
982
983         if (!safe_append_string(sid_list_buffer, sid_string,
984                                 sid_list_buffer_size)) {
985                 return false;
986         }
987
988         return true;
989 }
990
991 /**
992  * Convert a list of names into a list of sids.
993  *
994  * @param ctx PAM winbind context.
995  * @param user User in PAM request.
996  * @param name_list List of names or string sids, separated by commas.
997  * @param sid_list_buffer Where to put the list of string sids.
998  * @param sid_list_buffer Size of sid_list_buffer (in bytes).
999  *
1000  * @return false on failure, true on success.
1001  */
1002 static bool winbind_name_list_to_sid_string_list(struct pwb_context *ctx,
1003                                                  const char *user,
1004                                                  const char *name_list,
1005                                                  char *sid_list_buffer,
1006                                                  int sid_list_buffer_size)
1007 {
1008         bool result = false;
1009         char *current_name = NULL;
1010         const char *search_location;
1011         const char *comma;
1012
1013         if (sid_list_buffer_size > 0) {
1014                 sid_list_buffer[0] = 0;
1015         }
1016
1017         search_location = name_list;
1018         while ((comma = strstr(search_location, ",")) != NULL) {
1019                 current_name = strndup(search_location,
1020                                        comma - search_location);
1021                 if (NULL == current_name) {
1022                         goto out;
1023                 }
1024
1025                 if (!winbind_name_to_sid_string(ctx, user,
1026                                                 current_name,
1027                                                 sid_list_buffer,
1028                                                 sid_list_buffer_size)) {
1029                         goto out;
1030                 }
1031
1032                 SAFE_FREE(current_name);
1033
1034                 if (!safe_append_string(sid_list_buffer, ",",
1035                                         sid_list_buffer_size)) {
1036                         goto out;
1037                 }
1038
1039                 search_location = comma + 1;
1040         }
1041
1042         if (!winbind_name_to_sid_string(ctx, user, search_location,
1043                                         sid_list_buffer,
1044                                         sid_list_buffer_size)) {
1045                 goto out;
1046         }
1047
1048         result = true;
1049
1050 out:
1051         SAFE_FREE(current_name);
1052         return result;
1053 }
1054
1055 /**
1056  * put krb5ccname variable into environment
1057  *
1058  * @param ctx PAM winbind context.
1059  * @param krb5ccname env variable retrieved from winbindd.
1060  *
1061  * @return void.
1062  */
1063
1064 static void _pam_setup_krb5_env(struct pwb_context *ctx,
1065                                 struct wbcLogonUserInfo *info)
1066 {
1067         char var[PATH_MAX];
1068         int ret;
1069         uint32_t i;
1070         const char *krb5ccname = NULL;
1071
1072         if (off(ctx->ctrl, WINBIND_KRB5_AUTH)) {
1073                 return;
1074         }
1075
1076         if (!info) {
1077                 return;
1078         }
1079
1080         for (i=0; i < info->num_blobs; i++) {
1081                 if (strcasecmp(info->blobs[i].name, "krb5ccname") == 0) {
1082                         krb5ccname = (const char *)info->blobs[i].blob.data;
1083                         break;
1084                 }
1085         }
1086
1087         if (!krb5ccname || (strlen(krb5ccname) == 0)) {
1088                 return;
1089         }
1090
1091         _pam_log_debug(ctx, LOG_DEBUG,
1092                        "request returned KRB5CCNAME: %s", krb5ccname);
1093
1094         if (snprintf(var, sizeof(var), "KRB5CCNAME=%s", krb5ccname) == -1) {
1095                 return;
1096         }
1097
1098         ret = pam_putenv(ctx->pamh, var);
1099         if (ret) {
1100                 _pam_log(ctx, LOG_ERR,
1101                          "failed to set KRB5CCNAME to %s: %s",
1102                          var, pam_strerror(ctx->pamh, ret));
1103         }
1104 }
1105
1106 /**
1107  * Copy unix username if available (further processed in PAM).
1108  *
1109  * @param ctx PAM winbind context
1110  * @param user_ret A pointer that holds a pointer to a string
1111  * @param unix_username A username
1112  *
1113  * @return void.
1114  */
1115
1116 static void _pam_setup_unix_username(struct pwb_context *ctx,
1117                                      char **user_ret,
1118                                      struct wbcLogonUserInfo *info)
1119 {
1120         const char *unix_username = NULL;
1121         uint32_t i;
1122
1123         if (!user_ret || !info) {
1124                 return;
1125         }
1126
1127         for (i=0; i < info->num_blobs; i++) {
1128                 if (strcasecmp(info->blobs[i].name, "unix_username") == 0) {
1129                         unix_username = (const char *)info->blobs[i].blob.data;
1130                         break;
1131                 }
1132         }
1133
1134         if (!unix_username || !unix_username[0]) {
1135                 return;
1136         }
1137
1138         *user_ret = strdup(unix_username);
1139 }
1140
1141 /**
1142  * Set string into the PAM stack.
1143  *
1144  * @param ctx PAM winbind context.
1145  * @param data_name Key name for pam_set_data.
1146  * @param value String value.
1147  *
1148  * @return void.
1149  */
1150
1151 static void _pam_set_data_string(struct pwb_context *ctx,
1152                                  const char *data_name,
1153                                  const char *value)
1154 {
1155         int ret;
1156
1157         if (!data_name || !value || (strlen(data_name) == 0) ||
1158              (strlen(value) == 0)) {
1159                 return;
1160         }
1161
1162         ret = pam_set_data(ctx->pamh, data_name, talloc_strdup(NULL, value),
1163                            _pam_winbind_cleanup_func);
1164         if (ret) {
1165                 _pam_log_debug(ctx, LOG_DEBUG,
1166                                "Could not set data %s: %s\n",
1167                                data_name, pam_strerror(ctx->pamh, ret));
1168         }
1169 }
1170
1171 /**
1172  * Set info3 strings into the PAM stack.
1173  *
1174  * @param ctx PAM winbind context.
1175  * @param data_name Key name for pam_set_data.
1176  * @param value String value.
1177  *
1178  * @return void.
1179  */
1180
1181 static void _pam_set_data_info3(struct pwb_context *ctx,
1182                                 const struct wbcAuthUserInfo *info)
1183 {
1184         _pam_set_data_string(ctx, PAM_WINBIND_HOMEDIR,
1185                              info->home_directory);
1186         _pam_set_data_string(ctx, PAM_WINBIND_LOGONSCRIPT,
1187                              info->logon_script);
1188         _pam_set_data_string(ctx, PAM_WINBIND_LOGONSERVER,
1189                              info->logon_server);
1190         _pam_set_data_string(ctx, PAM_WINBIND_PROFILEPATH,
1191                              info->profile_path);
1192 }
1193
1194 /**
1195  * Free info3 strings in the PAM stack.
1196  *
1197  * @param pamh PAM handle
1198  *
1199  * @return void.
1200  */
1201
1202 static void _pam_free_data_info3(pam_handle_t *pamh)
1203 {
1204         pam_set_data(pamh, PAM_WINBIND_HOMEDIR, NULL, NULL);
1205         pam_set_data(pamh, PAM_WINBIND_LOGONSCRIPT, NULL, NULL);
1206         pam_set_data(pamh, PAM_WINBIND_LOGONSERVER, NULL, NULL);
1207         pam_set_data(pamh, PAM_WINBIND_PROFILEPATH, NULL, NULL);
1208 }
1209
1210 /**
1211  * Send PAM_ERROR_MSG for cached or grace logons.
1212  *
1213  * @param ctx PAM winbind context.
1214  * @param username User in PAM request.
1215  * @param info3_user_flgs Info3 flags containing logon type bits.
1216  *
1217  * @return void.
1218  */
1219
1220 static void _pam_warn_logon_type(struct pwb_context *ctx,
1221                                  const char *username,
1222                                  uint32_t info3_user_flgs)
1223 {
1224         /* inform about logon type */
1225         if (PAM_WB_GRACE_LOGON(info3_user_flgs)) {
1226
1227                 _make_remark(ctx, PAM_ERROR_MSG,
1228                              "Grace login. "
1229                              "Please change your password as soon you're "
1230                              "online again");
1231                 _pam_log_debug(ctx, LOG_DEBUG,
1232                                "User %s logged on using grace logon\n",
1233                                username);
1234
1235         } else if (PAM_WB_CACHED_LOGON(info3_user_flgs)) {
1236
1237                 _make_remark(ctx, PAM_ERROR_MSG,
1238                              "Domain Controller unreachable, "
1239                              "using cached credentials instead. "
1240                              "Network resources may be unavailable");
1241                 _pam_log_debug(ctx, LOG_DEBUG,
1242                                "User %s logged on using cached credentials\n",
1243                                username);
1244         }
1245 }
1246
1247 /**
1248  * Send PAM_ERROR_MSG for krb5 errors.
1249  *
1250  * @param ctx PAM winbind context.
1251  * @param username User in PAM request.
1252  * @param info3_user_flgs Info3 flags containing logon type bits.
1253  *
1254  * @return void.
1255  */
1256
1257 static void _pam_warn_krb5_failure(struct pwb_context *ctx,
1258                                    const char *username,
1259                                    uint32_t info3_user_flgs)
1260 {
1261         if (PAM_WB_KRB5_CLOCK_SKEW(info3_user_flgs)) {
1262                 _make_remark(ctx, PAM_ERROR_MSG,
1263                              "Failed to establish your Kerberos Ticket cache "
1264                              "due time differences\n"
1265                              "with the domain controller.  "
1266                              "Please verify the system time.\n");
1267                 _pam_log_debug(ctx, LOG_DEBUG,
1268                                "User %s: Clock skew when getting Krb5 TGT\n",
1269                                username);
1270         }
1271 }
1272
1273 static bool _pam_check_remark_auth_err(struct pwb_context *ctx,
1274                                        const struct wbcAuthErrorInfo *e,
1275                                        const char *nt_status_string,
1276                                        int *pam_error)
1277 {
1278         const char *ntstatus = NULL;
1279         const char *error_string = NULL;
1280
1281         if (!e || !pam_error) {
1282                 return false;
1283         }
1284
1285         ntstatus = e->nt_string;
1286         if (!ntstatus) {
1287                 return false;
1288         }
1289
1290         if (strcasecmp(ntstatus, nt_status_string) == 0) {
1291
1292                 error_string = _get_ntstatus_error_string(nt_status_string);
1293                 if (error_string) {
1294                         _make_remark(ctx, PAM_ERROR_MSG, error_string);
1295                         *pam_error = e->pam_error;
1296                         return true;
1297                 }
1298
1299                 if (e->display_string) {
1300                         _make_remark(ctx, PAM_ERROR_MSG, e->display_string);
1301                         *pam_error = e->pam_error;
1302                         return true;
1303                 }
1304
1305                 _make_remark(ctx, PAM_ERROR_MSG, nt_status_string);
1306                 *pam_error = e->pam_error;
1307
1308                 return true;
1309         }
1310
1311         return false;
1312 };
1313
1314 /**
1315  * Compose Password Restriction String for a PAM_ERROR_MSG conversation.
1316  *
1317  * @param i The wbcUserPasswordPolicyInfo struct.
1318  *
1319  * @return string (caller needs to talloc_free).
1320  */
1321
1322 static char *_pam_compose_pwd_restriction_string(struct pwb_context *ctx,
1323                                                  struct wbcUserPasswordPolicyInfo *i)
1324 {
1325         char *str = NULL;
1326
1327         if (!i) {
1328                 goto failed;
1329         }
1330
1331         str = talloc_asprintf(ctx, "Your password ");
1332         if (!str) {
1333                 goto failed;
1334         }
1335
1336         if (i->min_length_password > 0) {
1337                 str = talloc_asprintf_append(str,
1338                                "must be at least %d characters; ",
1339                                i->min_length_password);
1340                 if (!str) {
1341                         goto failed;
1342                 }
1343         }
1344
1345         if (i->password_history > 0) {
1346                 str = talloc_asprintf_append(str,
1347                                "cannot repeat any of your previous %d "
1348                                "passwords; ",
1349                                i->password_history);
1350                 if (!str) {
1351                         goto failed;
1352                 }
1353         }
1354
1355         if (i->password_properties & WBC_DOMAIN_PASSWORD_COMPLEX) {
1356                 str = talloc_asprintf_append(str,
1357                                "must contain capitals, numerals "
1358                                "or punctuation; "
1359                                "and cannot contain your account "
1360                                "or full name; ");
1361                 if (!str) {
1362                         goto failed;
1363                 }
1364         }
1365
1366         str = talloc_asprintf_append(str,
1367                        "Please type a different password. "
1368                        "Type a password which meets these requirements in "
1369                        "both text boxes.");
1370         if (!str) {
1371                 goto failed;
1372         }
1373
1374         return str;
1375
1376  failed:
1377         TALLOC_FREE(str);
1378         return NULL;
1379 }
1380
1381 /* talk to winbindd */
1382 static int winbind_auth_request(struct pwb_context *ctx,
1383                                 const char *user,
1384                                 const char *pass,
1385                                 const char *member,
1386                                 const char *cctype,
1387                                 const int warn_pwd_expire,
1388                                 struct wbcAuthErrorInfo **p_error,
1389                                 struct wbcLogonUserInfo **p_info,
1390                                 struct wbcUserPasswordPolicyInfo **p_policy,
1391                                 time_t *pwd_last_set,
1392                                 char **user_ret)
1393 {
1394         wbcErr wbc_status;
1395
1396         struct wbcLogonUserParams logon;
1397         char membership_of[1024];
1398         uid_t user_uid = -1;
1399         uint32_t flags = WBFLAG_PAM_INFO3_TEXT |
1400                          WBFLAG_PAM_GET_PWD_POLICY;
1401
1402         struct wbcLogonUserInfo *info = NULL;
1403         struct wbcAuthUserInfo *user_info = NULL;
1404         struct wbcAuthErrorInfo *error = NULL;
1405         struct wbcUserPasswordPolicyInfo *policy = NULL;
1406
1407         int ret = PAM_AUTH_ERR;
1408         int i;
1409         const char *codes[] = {
1410                 "NT_STATUS_PASSWORD_EXPIRED",
1411                 "NT_STATUS_PASSWORD_MUST_CHANGE",
1412                 "NT_STATUS_INVALID_WORKSTATION",
1413                 "NT_STATUS_INVALID_LOGON_HOURS",
1414                 "NT_STATUS_ACCOUNT_EXPIRED",
1415                 "NT_STATUS_ACCOUNT_DISABLED",
1416                 "NT_STATUS_ACCOUNT_LOCKED_OUT",
1417                 "NT_STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT",
1418                 "NT_STATUS_NOLOGON_SERVER_TRUST_ACCOUNT",
1419                 "NT_STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT",
1420                 "NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND",
1421                 "NT_STATUS_NO_LOGON_SERVERS",
1422                 "NT_STATUS_WRONG_PASSWORD",
1423                 "NT_STATUS_ACCESS_DENIED"
1424         };
1425
1426         if (pwd_last_set) {
1427                 *pwd_last_set = 0;
1428         }
1429
1430         /* Krb5 auth always has to go against the KDC of the user's realm */
1431
1432         if (ctx->ctrl & WINBIND_KRB5_AUTH) {
1433                 flags           |= WBFLAG_PAM_CONTACT_TRUSTDOM;
1434         }
1435
1436         if (ctx->ctrl & (WINBIND_KRB5_AUTH|WINBIND_CACHED_LOGIN)) {
1437                 struct passwd *pwd = NULL;
1438
1439                 pwd = getpwnam(user);
1440                 if (pwd == NULL) {
1441                         return PAM_USER_UNKNOWN;
1442                 }
1443                 user_uid        = pwd->pw_uid;
1444         }
1445
1446         if (ctx->ctrl & WINBIND_KRB5_AUTH) {
1447
1448                 _pam_log_debug(ctx, LOG_DEBUG,
1449                                "enabling krb5 login flag\n");
1450
1451                 flags           |= WBFLAG_PAM_KRB5 |
1452                                    WBFLAG_PAM_FALLBACK_AFTER_KRB5;
1453         }
1454
1455         if (ctx->ctrl & WINBIND_CACHED_LOGIN) {
1456                 _pam_log_debug(ctx, LOG_DEBUG,
1457                                "enabling cached login flag\n");
1458                 flags           |= WBFLAG_PAM_CACHED_LOGIN;
1459         }
1460
1461         if (user_ret) {
1462                 *user_ret = NULL;
1463                 flags           |= WBFLAG_PAM_UNIX_NAME;
1464         }
1465
1466         if (cctype != NULL) {
1467                 _pam_log_debug(ctx, LOG_DEBUG,
1468                                "enabling request for a %s krb5 ccache\n",
1469                                cctype);
1470         }
1471
1472         if (member != NULL) {
1473
1474                 ZERO_STRUCT(membership_of);
1475
1476                 if (!winbind_name_list_to_sid_string_list(ctx, user, member,
1477                                                           membership_of,
1478                                                           sizeof(membership_of))) {
1479                         _pam_log_debug(ctx, LOG_ERR,
1480                                        "failed to serialize membership of sid "
1481                                        "\"%s\"\n", member);
1482                         return PAM_AUTH_ERR;
1483                 }
1484         }
1485
1486         ZERO_STRUCT(logon);
1487
1488         logon.username                  = user;
1489         logon.password                  = pass;
1490
1491         wbc_status = wbcAddNamedBlob(&logon.num_blobs,
1492                                      &logon.blobs,
1493                                      "krb5_cc_type",
1494                                      0,
1495                                      (uint8_t *)cctype,
1496                                      strlen(cctype)+1);
1497         if (!WBC_ERROR_IS_OK(wbc_status)) {
1498                 goto done;
1499         }
1500
1501         wbc_status = wbcAddNamedBlob(&logon.num_blobs,
1502                                      &logon.blobs,
1503                                      "flags",
1504                                      0,
1505                                      (uint8_t *)&flags,
1506                                      sizeof(flags));
1507         if (!WBC_ERROR_IS_OK(wbc_status)) {
1508                 goto done;
1509         }
1510
1511         wbc_status = wbcAddNamedBlob(&logon.num_blobs,
1512                                      &logon.blobs,
1513                                      "user_uid",
1514                                      0,
1515                                      (uint8_t *)&user_uid,
1516                                      sizeof(user_uid));
1517         if (!WBC_ERROR_IS_OK(wbc_status)) {
1518                 goto done;
1519         }
1520
1521         wbc_status = wbcAddNamedBlob(&logon.num_blobs,
1522                                      &logon.blobs,
1523                                      "membership_of",
1524                                      0,
1525                                      (uint8_t *)membership_of,
1526                                      sizeof(membership_of));
1527         if (!WBC_ERROR_IS_OK(wbc_status)) {
1528                 goto done;
1529         }
1530
1531         wbc_status = wbcLogonUser(&logon, &info, &error, &policy);
1532         ret = wbc_auth_error_to_pam_error(ctx, error, wbc_status,
1533                                           user, "wbcLogonUser");
1534         wbcFreeMemory(logon.blobs);
1535         logon.blobs = NULL;
1536
1537         if (info && info->info) {
1538                 user_info = info->info;
1539         }
1540
1541         if (pwd_last_set && user_info) {
1542                 *pwd_last_set = user_info->pass_last_set_time;
1543         }
1544
1545         if (p_info && info) {
1546                 *p_info = info;
1547         }
1548
1549         if (p_policy && policy) {
1550                 *p_policy = policy;
1551         }
1552
1553         if (p_error && error) {
1554                 /* We want to process the error in the caller. */
1555                 *p_error = error;
1556                 return ret;
1557         }
1558
1559         for (i=0; i<ARRAY_SIZE(codes); i++) {
1560                 int _ret = ret;
1561                 if (_pam_check_remark_auth_err(ctx, error, codes[i], &_ret)) {
1562                         ret = _ret;
1563                         goto done;
1564                 }
1565         }
1566
1567         if ((ret == PAM_SUCCESS) && user_info && policy && info) {
1568
1569                 bool already_expired = false;
1570
1571                 /* warn a user if the password is about to expire soon */
1572                 _pam_warn_password_expiry(ctx, user_info, policy,
1573                                           warn_pwd_expire,
1574                                           &already_expired);
1575
1576                 if (already_expired == true) {
1577
1578                         SMB_TIME_T last_set = user_info->pass_last_set_time;
1579
1580                         _pam_log_debug(ctx, LOG_DEBUG,
1581                                        "Password has expired "
1582                                        "(Password was last set: %lld, "
1583                                        "the policy says it should expire here "
1584                                        "%lld (now it's: %lu))\n",
1585                                        (long long int)last_set,
1586                                        (long long int)last_set +
1587                                        policy->expire,
1588                                        time(NULL));
1589
1590                         return PAM_AUTHTOK_EXPIRED;
1591                 }
1592
1593                 /* inform about logon type */
1594                 _pam_warn_logon_type(ctx, user, user_info->user_flags);
1595
1596                 /* inform about krb5 failures */
1597                 _pam_warn_krb5_failure(ctx, user, user_info->user_flags);
1598
1599                 /* set some info3 info for other modules in the stack */
1600                 _pam_set_data_info3(ctx, user_info);
1601
1602                 /* put krb5ccname into env */
1603                 _pam_setup_krb5_env(ctx, info);
1604
1605                 /* If winbindd returned a username, return the pointer to it
1606                  * here. */
1607                 _pam_setup_unix_username(ctx, user_ret, info);
1608         }
1609
1610  done:
1611         if (logon.blobs) {
1612                 wbcFreeMemory(logon.blobs);
1613         }
1614         if (info && info->blobs) {
1615                 wbcFreeMemory(info->blobs);
1616         }
1617         if (error && !p_error) {
1618                 wbcFreeMemory(error);
1619         }
1620         if (info && !p_info) {
1621                 wbcFreeMemory(info);
1622         }
1623         if (policy && !p_policy) {
1624                 wbcFreeMemory(policy);
1625         }
1626
1627         return ret;
1628 }
1629
1630 /* talk to winbindd */
1631 static int winbind_chauthtok_request(struct pwb_context *ctx,
1632                                      const char *user,
1633                                      const char *oldpass,
1634                                      const char *newpass,
1635                                      time_t pwd_last_set)
1636 {
1637         wbcErr wbc_status;
1638         struct wbcChangePasswordParams params;
1639         struct wbcAuthErrorInfo *error = NULL;
1640         struct wbcUserPasswordPolicyInfo *policy = NULL;
1641         enum wbcPasswordChangeRejectReason reject_reason = -1;
1642         uint32_t flags = 0;
1643
1644         int i;
1645         const char *codes[] = {
1646                 "NT_STATUS_BACKUP_CONTROLLER",
1647                 "NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND",
1648                 "NT_STATUS_NO_LOGON_SERVERS",
1649                 "NT_STATUS_ACCESS_DENIED",
1650                 "NT_STATUS_PWD_TOO_SHORT", /* TODO: tell the min pwd length ? */
1651                 "NT_STATUS_PWD_TOO_RECENT", /* TODO: tell the minage ? */
1652                 "NT_STATUS_PWD_HISTORY_CONFLICT" /* TODO: tell the history length ? */
1653         };
1654         int ret = PAM_AUTH_ERR;
1655
1656         ZERO_STRUCT(params);
1657
1658         if (ctx->ctrl & WINBIND_KRB5_AUTH) {
1659                 flags |= WBFLAG_PAM_KRB5 |
1660                          WBFLAG_PAM_CONTACT_TRUSTDOM;
1661         }
1662
1663         if (ctx->ctrl & WINBIND_CACHED_LOGIN) {
1664                 flags |= WBFLAG_PAM_CACHED_LOGIN;
1665         }
1666
1667         params.account_name             = user;
1668         params.level                    = WBC_AUTH_USER_LEVEL_PLAIN;
1669         params.old_password.plaintext   = oldpass;
1670         params.new_password.plaintext   = newpass;
1671         params.flags                    = flags;
1672
1673         wbc_status = wbcChangeUserPasswordEx(&params, &error, &reject_reason, &policy);
1674         ret = wbc_auth_error_to_pam_error(ctx, error, wbc_status,
1675                                           user, "wbcChangeUserPasswordEx");
1676
1677         if (WBC_ERROR_IS_OK(wbc_status)) {
1678                 _pam_log(ctx, LOG_NOTICE,
1679                          "user '%s' password changed", user);
1680                 return PAM_SUCCESS;
1681         }
1682
1683         if (!error) {
1684                 wbcFreeMemory(policy);
1685                 return ret;
1686         }
1687
1688         for (i=0; i<ARRAY_SIZE(codes); i++) {
1689                 int _ret = ret;
1690                 if (_pam_check_remark_auth_err(ctx, error, codes[i], &_ret)) {
1691                         ret = _ret;
1692                         goto done;
1693                 }
1694         }
1695
1696         if (!strcasecmp(error->nt_string,
1697                         "NT_STATUS_PASSWORD_RESTRICTION")) {
1698
1699                 char *pwd_restriction_string = NULL;
1700                 SMB_TIME_T min_pwd_age = 0;
1701
1702                 if (policy) {
1703                         min_pwd_age     = policy->min_passwordage;
1704                 }
1705
1706                 /* FIXME: avoid to send multiple PAM messages after another */
1707                 switch (reject_reason) {
1708                         case -1:
1709                                 break;
1710                         case WBC_PWD_CHANGE_REJECT_OTHER:
1711                                 if ((min_pwd_age > 0) &&
1712                                     (pwd_last_set + min_pwd_age > time(NULL))) {
1713                                         PAM_WB_REMARK_DIRECT(ctx,
1714                                              "NT_STATUS_PWD_TOO_RECENT");
1715                                 }
1716                                 break;
1717                         case WBC_PWD_CHANGE_REJECT_TOO_SHORT:
1718                                 PAM_WB_REMARK_DIRECT(ctx,
1719                                         "NT_STATUS_PWD_TOO_SHORT");
1720                                 break;
1721                         case WBC_PWD_CHANGE_REJECT_IN_HISTORY:
1722                                 PAM_WB_REMARK_DIRECT(ctx,
1723                                         "NT_STATUS_PWD_HISTORY_CONFLICT");
1724                                 break;
1725                         case WBC_PWD_CHANGE_REJECT_COMPLEXITY:
1726                                 _make_remark(ctx, PAM_ERROR_MSG,
1727                                              "Password does not meet "
1728                                              "complexity requirements");
1729                                 break;
1730                         default:
1731                                 _pam_log_debug(ctx, LOG_DEBUG,
1732                                                "unknown password change "
1733                                                "reject reason: %d",
1734                                                reject_reason);
1735                                 break;
1736                 }
1737
1738                 pwd_restriction_string =
1739                         _pam_compose_pwd_restriction_string(ctx, policy);
1740                 if (pwd_restriction_string) {
1741                         _make_remark(ctx, PAM_ERROR_MSG,
1742                                      pwd_restriction_string);
1743                         TALLOC_FREE(pwd_restriction_string);
1744                 }
1745         }
1746  done:
1747         wbcFreeMemory(error);
1748         wbcFreeMemory(policy);
1749
1750         return ret;
1751 }
1752
1753 /*
1754  * Checks if a user has an account
1755  *
1756  * return values:
1757  *       1  = User not found
1758  *       0  = OK
1759  *      -1  = System error
1760  */
1761 static int valid_user(struct pwb_context *ctx,
1762                       const char *user)
1763 {
1764         /* check not only if the user is available over NSS calls, also make
1765          * sure it's really a winbind user, this is important when stacking PAM
1766          * modules in the 'account' or 'password' facility. */
1767
1768         wbcErr wbc_status;
1769         struct passwd *pwd = NULL;
1770         struct passwd *wb_pwd = NULL;
1771
1772         pwd = getpwnam(user);
1773         if (pwd == NULL) {
1774                 return 1;
1775         }
1776
1777         wbc_status = wbcGetpwnam(user, &wb_pwd);
1778         wbcFreeMemory(wb_pwd);
1779         if (!WBC_ERROR_IS_OK(wbc_status)) {
1780                 _pam_log(ctx, LOG_DEBUG, "valid_user: wbcGetpwnam gave %s\n",
1781                         wbcErrorString(wbc_status));
1782         }
1783
1784         switch (wbc_status) {
1785                 case WBC_ERR_UNKNOWN_USER:
1786                         return 1;
1787                 case WBC_ERR_SUCCESS:
1788                         return 0;
1789                 default:
1790                         break;
1791         }
1792         return -1;
1793 }
1794
1795 static char *_pam_delete(register char *xx)
1796 {
1797         _pam_overwrite(xx);
1798         _pam_drop(xx);
1799         return NULL;
1800 }
1801
1802 /*
1803  * obtain a password from the user
1804  */
1805
1806 static int _winbind_read_password(struct pwb_context *ctx,
1807                                   unsigned int ctrl,
1808                                   const char *comment,
1809                                   const char *prompt1,
1810                                   const char *prompt2,
1811                                   const char **pass)
1812 {
1813         int authtok_flag;
1814         int retval;
1815         const char *item;
1816         char *token;
1817
1818         _pam_log(ctx, LOG_DEBUG, "getting password (0x%08x)", ctrl);
1819
1820         /*
1821          * make sure nothing inappropriate gets returned
1822          */
1823
1824         *pass = token = NULL;
1825
1826         /*
1827          * which authentication token are we getting?
1828          */
1829
1830         if (on(WINBIND__OLD_PASSWORD, ctrl)) {
1831                 authtok_flag = PAM_OLDAUTHTOK;
1832         } else {
1833                 authtok_flag = PAM_AUTHTOK;
1834         }
1835
1836         /*
1837          * should we obtain the password from a PAM item ?
1838          */
1839
1840         if (on(WINBIND_TRY_FIRST_PASS_ARG, ctrl) ||
1841             on(WINBIND_USE_FIRST_PASS_ARG, ctrl)) {
1842                 retval = _pam_get_item(ctx->pamh, authtok_flag, &item);
1843                 if (retval != PAM_SUCCESS) {
1844                         /* very strange. */
1845                         _pam_log(ctx, LOG_ALERT,
1846                                  "pam_get_item returned error "
1847                                  "to unix-read-password");
1848                         return retval;
1849                 } else if (item != NULL) {      /* we have a password! */
1850                         *pass = item;
1851                         item = NULL;
1852                         _pam_log(ctx, LOG_DEBUG,
1853                                  "pam_get_item returned a password");
1854                         return PAM_SUCCESS;
1855                 } else if (on(WINBIND_USE_FIRST_PASS_ARG, ctrl)) {
1856                         return PAM_AUTHTOK_RECOVER_ERR; /* didn't work */
1857                 } else if (on(WINBIND_USE_AUTHTOK_ARG, ctrl)
1858                            && off(WINBIND__OLD_PASSWORD, ctrl)) {
1859                         return PAM_AUTHTOK_RECOVER_ERR;
1860                 }
1861         }
1862         /*
1863          * getting here implies we will have to get the password from the
1864          * user directly.
1865          */
1866
1867         {
1868                 struct pam_message msg[3], *pmsg[3];
1869                 struct pam_response *resp;
1870                 int i, replies;
1871
1872                 /* prepare to converse */
1873
1874                 if (comment != NULL && off(ctrl, WINBIND_SILENT)) {
1875                         pmsg[0] = &msg[0];
1876                         msg[0].msg_style = PAM_TEXT_INFO;
1877                         msg[0].msg = discard_const_p(char, comment);
1878                         i = 1;
1879                 } else {
1880                         i = 0;
1881                 }
1882
1883                 pmsg[i] = &msg[i];
1884                 msg[i].msg_style = PAM_PROMPT_ECHO_OFF;
1885                 msg[i++].msg = discard_const_p(char, prompt1);
1886                 replies = 1;
1887
1888                 if (prompt2 != NULL) {
1889                         pmsg[i] = &msg[i];
1890                         msg[i].msg_style = PAM_PROMPT_ECHO_OFF;
1891                         msg[i++].msg = discard_const_p(char, prompt2);
1892                         ++replies;
1893                 }
1894                 /* so call the conversation expecting i responses */
1895                 resp = NULL;
1896                 retval = converse(ctx->pamh, i, pmsg, &resp);
1897                 if (resp == NULL) {
1898                         if (retval == PAM_SUCCESS) {
1899                                 retval = PAM_AUTHTOK_RECOVER_ERR;
1900                         }
1901                         goto done;
1902                 }
1903                 if (retval != PAM_SUCCESS) {
1904                         _pam_drop_reply(resp, i);
1905                         goto done;
1906                 }
1907
1908                 /* interpret the response */
1909
1910                 token = x_strdup(resp[i - replies].resp);
1911                 if (!token) {
1912                         _pam_log(ctx, LOG_NOTICE,
1913                                  "could not recover "
1914                                  "authentication token");
1915                         retval = PAM_AUTHTOK_RECOVER_ERR;
1916                         goto done;
1917                 }
1918
1919                 if (replies == 2) {
1920                         /* verify that password entered correctly */
1921                         if (!resp[i - 1].resp ||
1922                             strcmp(token, resp[i - 1].resp)) {
1923                                 _pam_delete(token);     /* mistyped */
1924                                 retval = PAM_AUTHTOK_RECOVER_ERR;
1925                                 _make_remark(ctx, PAM_ERROR_MSG,
1926                                              MISTYPED_PASS);
1927                         }
1928                 }
1929
1930                 /*
1931                  * tidy up the conversation (resp_retcode) is ignored
1932                  * -- what is it for anyway? AGM
1933                  */
1934                 _pam_drop_reply(resp, i);
1935         }
1936
1937  done:
1938         if (retval != PAM_SUCCESS) {
1939                 _pam_log_debug(ctx, LOG_DEBUG,
1940                                "unable to obtain a password");
1941                 return retval;
1942         }
1943         /* 'token' is the entered password */
1944
1945         /* we store this password as an item */
1946
1947         retval = pam_set_item(ctx->pamh, authtok_flag, token);
1948         _pam_delete(token);     /* clean it up */
1949         if (retval != PAM_SUCCESS ||
1950             (retval = _pam_get_item(ctx->pamh, authtok_flag, &item)) != PAM_SUCCESS) {
1951
1952                 _pam_log(ctx, LOG_CRIT, "error manipulating password");
1953                 return retval;
1954
1955         }
1956
1957         *pass = item;
1958         item = NULL;            /* break link to password */
1959
1960         return PAM_SUCCESS;
1961 }
1962
1963 static const char *get_conf_item_string(struct pwb_context *ctx,
1964                                         const char *item,
1965                                         int config_flag)
1966 {
1967         int i = 0;
1968         const char *parm_opt = NULL;
1969
1970         if (!(ctx->ctrl & config_flag)) {
1971                 goto out;
1972         }
1973
1974         /* let the pam opt take precedence over the pam_winbind.conf option */
1975         for (i=0; i<ctx->argc; i++) {
1976
1977                 if ((strncmp(ctx->argv[i], item, strlen(item)) == 0)) {
1978                         char *p;
1979
1980                         if ((p = strchr(ctx->argv[i], '=')) == NULL) {
1981                                 _pam_log(ctx, LOG_INFO,
1982                                          "no \"=\" delimiter for \"%s\" found\n",
1983                                          item);
1984                                 goto out;
1985                         }
1986                         _pam_log_debug(ctx, LOG_INFO,
1987                                        "PAM config: %s '%s'\n", item, p+1);
1988                         return p + 1;
1989                 }
1990         }
1991
1992         if (ctx->dict) {
1993                 char *key = NULL;
1994
1995                 key = talloc_asprintf(ctx, "global:%s", item);
1996                 if (!key) {
1997                         goto out;
1998                 }
1999
2000                 parm_opt = iniparser_getstr(ctx->dict, key);
2001                 TALLOC_FREE(key);
2002
2003                 _pam_log_debug(ctx, LOG_INFO, "CONFIG file: %s '%s'\n",
2004                                item, parm_opt);
2005         }
2006 out:
2007         return parm_opt;
2008 }
2009
2010 static int get_config_item_int(struct pwb_context *ctx,
2011                                const char *item,
2012                                int config_flag)
2013 {
2014         int i, parm_opt = -1;
2015
2016         if (!(ctx->ctrl & config_flag)) {
2017                 goto out;
2018         }
2019
2020         /* let the pam opt take precedence over the pam_winbind.conf option */
2021         for (i = 0; i < ctx->argc; i++) {
2022
2023                 if ((strncmp(ctx->argv[i], item, strlen(item)) == 0)) {
2024                         char *p;
2025
2026                         if ((p = strchr(ctx->argv[i], '=')) == NULL) {
2027                                 _pam_log(ctx, LOG_INFO,
2028                                          "no \"=\" delimiter for \"%s\" found\n",
2029                                          item);
2030                                 goto out;
2031                         }
2032                         parm_opt = atoi(p + 1);
2033                         _pam_log_debug(ctx, LOG_INFO,
2034                                        "PAM config: %s '%d'\n",
2035                                        item, parm_opt);
2036                         return parm_opt;
2037                 }
2038         }
2039
2040         if (ctx->dict) {
2041                 char *key = NULL;
2042
2043                 key = talloc_asprintf(ctx, "global:%s", item);
2044                 if (!key) {
2045                         goto out;
2046                 }
2047
2048                 parm_opt = iniparser_getint(ctx->dict, key, -1);
2049                 TALLOC_FREE(key);
2050
2051                 _pam_log_debug(ctx, LOG_INFO,
2052                                "CONFIG file: %s '%d'\n",
2053                                item, parm_opt);
2054         }
2055 out:
2056         return parm_opt;
2057 }
2058
2059 static const char *get_krb5_cc_type_from_config(struct pwb_context *ctx)
2060 {
2061         return get_conf_item_string(ctx, "krb5_ccache_type",
2062                                     WINBIND_KRB5_CCACHE_TYPE);
2063 }
2064
2065 static const char *get_member_from_config(struct pwb_context *ctx)
2066 {
2067         const char *ret = NULL;
2068         ret = get_conf_item_string(ctx, "require_membership_of",
2069                                    WINBIND_REQUIRED_MEMBERSHIP);
2070         if (ret) {
2071                 return ret;
2072         }
2073         return get_conf_item_string(ctx, "require-membership-of",
2074                                     WINBIND_REQUIRED_MEMBERSHIP);
2075 }
2076
2077 static int get_warn_pwd_expire_from_config(struct pwb_context *ctx)
2078 {
2079         int ret;
2080         ret = get_config_item_int(ctx, "warn_pwd_expire",
2081                                   WINBIND_WARN_PWD_EXPIRE);
2082         /* no or broken setting */
2083         if (ret <= 0) {
2084                 return DEFAULT_DAYS_TO_WARN_BEFORE_PWD_EXPIRES;
2085         }
2086         return ret;
2087 }
2088
2089 /**
2090  * Retrieve the winbind separator.
2091  *
2092  * @param ctx PAM winbind context.
2093  *
2094  * @return string separator character. NULL on failure.
2095  */
2096
2097 static char winbind_get_separator(struct pwb_context *ctx)
2098 {
2099         wbcErr wbc_status;
2100         static struct wbcInterfaceDetails *details = NULL;
2101
2102         wbc_status = wbcInterfaceDetails(&details);
2103         if (!WBC_ERROR_IS_OK(wbc_status)) {
2104                 _pam_log(ctx, LOG_ERR,
2105                          "Could not retrieve winbind interface details: %s",
2106                          wbcErrorString(wbc_status));
2107                 return '\0';
2108         }
2109
2110         if (!details) {
2111                 return '\0';
2112         }
2113
2114         return details->winbind_separator;
2115 }
2116
2117
2118 /**
2119  * Convert a upn to a name.
2120  *
2121  * @param ctx PAM winbind context.
2122  * @param upn  USer UPN to be trabslated.
2123  *
2124  * @return converted name. NULL pointer on failure. Caller needs to free.
2125  */
2126
2127 static char* winbind_upn_to_username(struct pwb_context *ctx,
2128                                      const char *upn)
2129 {
2130         char sep;
2131         wbcErr wbc_status = WBC_ERR_UNKNOWN_FAILURE;
2132         struct wbcDomainSid sid;
2133         enum wbcSidType type;
2134         char *domain;
2135         char *name;
2136
2137         /* This cannot work when the winbind separator = @ */
2138
2139         sep = winbind_get_separator(ctx);
2140         if (!sep || sep == '@') {
2141                 return NULL;
2142         }
2143
2144         /* Convert the UPN to a SID */
2145
2146         wbc_status = wbcLookupName("", upn, &sid, &type);
2147         if (!WBC_ERROR_IS_OK(wbc_status)) {
2148                 return NULL;
2149         }
2150
2151         /* Convert the the SID back to the sAMAccountName */
2152
2153         wbc_status = wbcLookupSid(&sid, &domain, &name, &type);
2154         if (!WBC_ERROR_IS_OK(wbc_status)) {
2155                 return NULL;
2156         }
2157
2158         return talloc_asprintf(ctx, "%s\\%s", domain, name);
2159 }
2160
2161 PAM_EXTERN
2162 int pam_sm_authenticate(pam_handle_t *pamh, int flags,
2163                         int argc, const char **argv)
2164 {
2165         const char *username;
2166         const char *password;
2167         const char *member = NULL;
2168         const char *cctype = NULL;
2169         int warn_pwd_expire;
2170         int retval = PAM_AUTH_ERR;
2171         char *username_ret = NULL;
2172         char *new_authtok_required = NULL;
2173         char *real_username = NULL;
2174         struct pwb_context *ctx = NULL;
2175
2176         retval = _pam_winbind_init_context(pamh, flags, argc, argv, &ctx);
2177         if (retval) {
2178                 goto out;
2179         }
2180
2181         _PAM_LOG_FUNCTION_ENTER("pam_sm_authenticate", ctx);
2182
2183         /* Get the username */
2184         retval = pam_get_user(pamh, &username, NULL);
2185         if ((retval != PAM_SUCCESS) || (!username)) {
2186                 _pam_log_debug(ctx, LOG_DEBUG,
2187                                "can not get the username");
2188                 retval = PAM_SERVICE_ERR;
2189                 goto out;
2190         }
2191
2192
2193 #if defined(AIX)
2194         /* Decode the user name since AIX does not support logn user
2195            names by default.  The name is encoded as _#uid.  */
2196
2197         if (username[0] == '_') {
2198                 uid_t id = atoi(&username[1]);
2199                 struct passwd *pw = NULL;
2200
2201                 if ((id!=0) && ((pw = getpwuid(id)) != NULL)) {
2202                         real_username = strdup(pw->pw_name);
2203                 }
2204         }
2205 #endif
2206
2207         if (!real_username) {
2208                 /* Just making a copy of the username we got from PAM */
2209                 if ((real_username = strdup(username)) == NULL) {
2210                         _pam_log_debug(ctx, LOG_DEBUG,
2211                                        "memory allocation failure when copying "
2212                                        "username");
2213                         retval = PAM_SERVICE_ERR;
2214                         goto out;
2215                 }
2216         }
2217
2218         /* Maybe this was a UPN */
2219
2220         if (strchr(real_username, '@') != NULL) {
2221                 char *samaccountname = NULL;
2222
2223                 samaccountname = winbind_upn_to_username(ctx,
2224                                                          real_username);
2225                 if (samaccountname) {
2226                         free(real_username);
2227                         real_username = strdup(samaccountname);
2228                 }
2229         }
2230
2231         retval = _winbind_read_password(ctx, ctx->ctrl, NULL,
2232                                         "Password: ", NULL,
2233                                         &password);
2234
2235         if (retval != PAM_SUCCESS) {
2236                 _pam_log(ctx, LOG_ERR,
2237                          "Could not retrieve user's password");
2238                 retval = PAM_AUTHTOK_ERR;
2239                 goto out;
2240         }
2241
2242         /* Let's not give too much away in the log file */
2243
2244 #ifdef DEBUG_PASSWORD
2245         _pam_log_debug(ctx, LOG_INFO,
2246                        "Verify user '%s' with password '%s'",
2247                        real_username, password);
2248 #else
2249         _pam_log_debug(ctx, LOG_INFO,
2250                        "Verify user '%s'", real_username);
2251 #endif
2252
2253         member = get_member_from_config(ctx);
2254         cctype = get_krb5_cc_type_from_config(ctx);
2255         warn_pwd_expire = get_warn_pwd_expire_from_config(ctx);
2256
2257         /* Now use the username to look up password */
2258         retval = winbind_auth_request(ctx, real_username, password,
2259                                       member, cctype, warn_pwd_expire,
2260                                       NULL, NULL, NULL,
2261                                       NULL, &username_ret);
2262
2263         if (retval == PAM_NEW_AUTHTOK_REQD ||
2264             retval == PAM_AUTHTOK_EXPIRED) {
2265
2266                 char *new_authtok_required_during_auth = NULL;
2267
2268                 new_authtok_required = talloc_asprintf(NULL, "%d", retval);
2269                 if (!new_authtok_required) {
2270                         retval = PAM_BUF_ERR;
2271                         goto out;
2272                 }
2273
2274                 pam_set_data(pamh, PAM_WINBIND_NEW_AUTHTOK_REQD,
2275                              new_authtok_required,
2276                              _pam_winbind_cleanup_func);
2277
2278                 retval = PAM_SUCCESS;
2279
2280                 new_authtok_required_during_auth = talloc_asprintf(NULL, "%d", true);
2281                 if (!new_authtok_required_during_auth) {
2282                         retval = PAM_BUF_ERR;
2283                         goto out;
2284                 }
2285
2286                 pam_set_data(pamh, PAM_WINBIND_NEW_AUTHTOK_REQD_DURING_AUTH,
2287                              new_authtok_required_during_auth,
2288                              _pam_winbind_cleanup_func);
2289
2290                 goto out;
2291         }
2292
2293 out:
2294         if (username_ret) {
2295                 pam_set_item (pamh, PAM_USER, username_ret);
2296                 _pam_log_debug(ctx, LOG_INFO,
2297                                "Returned user was '%s'", username_ret);
2298                 free(username_ret);
2299         }
2300
2301         if (real_username) {
2302                 free(real_username);
2303         }
2304
2305         if (!new_authtok_required) {
2306                 pam_set_data(pamh, PAM_WINBIND_NEW_AUTHTOK_REQD, NULL, NULL);
2307         }
2308
2309         if (retval != PAM_SUCCESS) {
2310                 _pam_free_data_info3(pamh);
2311         }
2312
2313         _PAM_LOG_FUNCTION_LEAVE("pam_sm_authenticate", ctx, retval);
2314
2315         TALLOC_FREE(ctx);
2316
2317         return retval;
2318 }
2319
2320 PAM_EXTERN
2321 int pam_sm_setcred(pam_handle_t *pamh, int flags,
2322                    int argc, const char **argv)
2323 {
2324         int ret = PAM_SYSTEM_ERR;
2325         struct pwb_context *ctx = NULL;
2326
2327         ret = _pam_winbind_init_context(pamh, flags, argc, argv, &ctx);
2328         if (ret) {
2329                 goto out;
2330         }
2331
2332         _PAM_LOG_FUNCTION_ENTER("pam_sm_setcred", ctx);
2333
2334         switch (flags & ~PAM_SILENT) {
2335
2336                 case PAM_DELETE_CRED:
2337                         ret = pam_sm_close_session(pamh, flags, argc, argv);
2338                         break;
2339                 case PAM_REFRESH_CRED:
2340                         _pam_log_debug(ctx, LOG_WARNING,
2341                                        "PAM_REFRESH_CRED not implemented");
2342                         ret = PAM_SUCCESS;
2343                         break;
2344                 case PAM_REINITIALIZE_CRED:
2345                         _pam_log_debug(ctx, LOG_WARNING,
2346                                        "PAM_REINITIALIZE_CRED not implemented");
2347                         ret = PAM_SUCCESS;
2348                         break;
2349                 case PAM_ESTABLISH_CRED:
2350                         _pam_log_debug(ctx, LOG_WARNING,
2351                                        "PAM_ESTABLISH_CRED not implemented");
2352                         ret = PAM_SUCCESS;
2353                         break;
2354                 default:
2355                         ret = PAM_SYSTEM_ERR;
2356                         break;
2357         }
2358
2359  out:
2360
2361         _PAM_LOG_FUNCTION_LEAVE("pam_sm_setcred", ctx, ret);
2362
2363         TALLOC_FREE(ctx);
2364
2365         return ret;
2366 }
2367
2368 /*
2369  * Account management. We want to verify that the account exists
2370  * before returning PAM_SUCCESS
2371  */
2372 PAM_EXTERN
2373 int pam_sm_acct_mgmt(pam_handle_t *pamh, int flags,
2374                    int argc, const char **argv)
2375 {
2376         const char *username;
2377         int ret = PAM_USER_UNKNOWN;
2378         void *tmp = NULL;
2379         struct pwb_context *ctx = NULL;
2380
2381         ret = _pam_winbind_init_context(pamh, flags, argc, argv, &ctx);
2382         if (ret) {
2383                 goto out;
2384         }
2385
2386         _PAM_LOG_FUNCTION_ENTER("pam_sm_acct_mgmt", ctx);
2387
2388
2389         /* Get the username */
2390         ret = pam_get_user(pamh, &username, NULL);
2391         if ((ret != PAM_SUCCESS) || (!username)) {
2392                 _pam_log_debug(ctx, LOG_DEBUG,
2393                                "can not get the username");
2394                 ret = PAM_SERVICE_ERR;
2395                 goto out;
2396         }
2397
2398         /* Verify the username */
2399         ret = valid_user(ctx, username);
2400         switch (ret) {
2401         case -1:
2402                 /* some sort of system error. The log was already printed */
2403                 ret = PAM_SERVICE_ERR;
2404                 goto out;
2405         case 1:
2406                 /* the user does not exist */
2407                 _pam_log_debug(ctx, LOG_NOTICE, "user '%s' not found",
2408                                username);
2409                 if (ctx->ctrl & WINBIND_UNKNOWN_OK_ARG) {
2410                         ret = PAM_IGNORE;
2411                         goto out;
2412                 }
2413                 ret = PAM_USER_UNKNOWN;
2414                 goto out;
2415         case 0:
2416                 pam_get_data(pamh, PAM_WINBIND_NEW_AUTHTOK_REQD,
2417                              (const void **)&tmp);
2418                 if (tmp != NULL) {
2419                         ret = atoi((const char *)tmp);
2420                         switch (ret) {
2421                         case PAM_AUTHTOK_EXPIRED:
2422                                 /* fall through, since new token is required in this case */
2423                         case PAM_NEW_AUTHTOK_REQD:
2424                                 _pam_log(ctx, LOG_WARNING,
2425                                          "pam_sm_acct_mgmt success but %s is set",
2426                                          PAM_WINBIND_NEW_AUTHTOK_REQD);
2427                                 _pam_log(ctx, LOG_NOTICE,
2428                                          "user '%s' needs new password",
2429                                          username);
2430                                 /* PAM_AUTHTOKEN_REQD does not exist, but is documented in the manpage */
2431                                 ret = PAM_NEW_AUTHTOK_REQD;
2432                                 goto out;
2433                         default:
2434                                 _pam_log(ctx, LOG_WARNING,
2435                                          "pam_sm_acct_mgmt success");
2436                                 _pam_log(ctx, LOG_NOTICE,
2437                                          "user '%s' granted access", username);
2438                                 ret = PAM_SUCCESS;
2439                                 goto out;
2440                         }
2441                 }
2442
2443                 /* Otherwise, the authentication looked good */
2444                 _pam_log(ctx, LOG_NOTICE,
2445                          "user '%s' granted access", username);
2446                 ret = PAM_SUCCESS;
2447                 goto out;
2448         default:
2449                 /* we don't know anything about this return value */
2450                 _pam_log(ctx, LOG_ERR,
2451                          "internal module error (ret = %d, user = '%s')",
2452                          ret, username);
2453                 ret = PAM_SERVICE_ERR;
2454                 goto out;
2455         }
2456
2457         /* should not be reached */
2458         ret = PAM_IGNORE;
2459
2460  out:
2461
2462         _PAM_LOG_FUNCTION_LEAVE("pam_sm_acct_mgmt", ctx, ret);
2463
2464         TALLOC_FREE(ctx);
2465
2466         return ret;
2467 }
2468
2469 PAM_EXTERN
2470 int pam_sm_open_session(pam_handle_t *pamh, int flags,
2471                         int argc, const char **argv)
2472 {
2473         int ret = PAM_SYSTEM_ERR;
2474         struct pwb_context *ctx = NULL;
2475
2476         ret = _pam_winbind_init_context(pamh, flags, argc, argv, &ctx);
2477         if (ret) {
2478                 goto out;
2479         }
2480
2481         _PAM_LOG_FUNCTION_ENTER("pam_sm_open_session", ctx);
2482
2483         ret = PAM_SUCCESS;
2484
2485  out:
2486         _PAM_LOG_FUNCTION_LEAVE("pam_sm_open_session", ctx, ret);
2487
2488         TALLOC_FREE(ctx);
2489
2490         return ret;
2491 }
2492
2493 PAM_EXTERN
2494 int pam_sm_close_session(pam_handle_t *pamh, int flags,
2495                          int argc, const char **argv)
2496 {
2497         int retval = PAM_SUCCESS;
2498         struct pwb_context *ctx = NULL;
2499         struct wbcLogoffUserParams logoff;
2500
2501         retval = _pam_winbind_init_context(pamh, flags, argc, argv, &ctx);
2502         if (retval) {
2503                 goto out;
2504         }
2505
2506         _PAM_LOG_FUNCTION_ENTER("pam_sm_close_session", ctx);
2507
2508         if (!(flags & PAM_DELETE_CRED)) {
2509                 retval = PAM_SUCCESS;
2510                 goto out;
2511         }
2512
2513         if (ctx->ctrl & WINBIND_KRB5_AUTH) {
2514
2515                 /* destroy the ccache here */
2516
2517                 wbcErr wbc_status;
2518                 struct wbcAuthErrorInfo *error = NULL;
2519
2520                 uint32_t flags = 0;
2521                 const char *user;
2522                 const char *ccname = NULL;
2523                 struct passwd *pwd = NULL;
2524
2525                 retval = pam_get_user(pamh, &user, "Username: ");
2526                 if (retval) {
2527                         _pam_log(ctx, LOG_ERR,
2528                                  "could not identify user");
2529                         goto out;
2530                 }
2531
2532                 if (user == NULL) {
2533                         _pam_log(ctx, LOG_ERR,
2534                                  "username was NULL!");
2535                         retval = PAM_USER_UNKNOWN;
2536                         goto out;
2537                 }
2538
2539                 _pam_log_debug(ctx, LOG_DEBUG,
2540                                "username [%s] obtained", user);
2541
2542                 ccname = pam_getenv(pamh, "KRB5CCNAME");
2543                 if (ccname == NULL) {
2544                         _pam_log_debug(ctx, LOG_DEBUG,
2545                                        "user has no KRB5CCNAME environment");
2546                 }
2547
2548                 pwd = getpwnam(user);
2549                 if (pwd == NULL) {
2550                         retval = PAM_USER_UNKNOWN;
2551                         goto out;
2552                 }
2553
2554                 flags = WBFLAG_PAM_KRB5 |
2555                         WBFLAG_PAM_CONTACT_TRUSTDOM;
2556
2557                 ZERO_STRUCT(logoff);
2558
2559                 logoff.username         = user;
2560
2561                 wbc_status = wbcAddNamedBlob(&logoff.num_blobs,
2562                                              &logoff.blobs,
2563                                              "ccfilename",
2564                                              0,
2565                                              (uint8_t *)ccname,
2566                                              strlen(ccname)+1);
2567                 if (!WBC_ERROR_IS_OK(wbc_status)) {
2568                         goto out;
2569                 }
2570
2571                 wbc_status = wbcAddNamedBlob(&logoff.num_blobs,
2572                                              &logoff.blobs,
2573                                              "flags",
2574                                              0,
2575                                              (uint8_t *)&flags,
2576                                              sizeof(flags));
2577                 if (!WBC_ERROR_IS_OK(wbc_status)) {
2578                         goto out;
2579                 }
2580
2581                 wbc_status = wbcAddNamedBlob(&logoff.num_blobs,
2582                                              &logoff.blobs,
2583                                              "user_uid",
2584                                              0,
2585                                              (uint8_t *)&pwd->pw_uid,
2586                                              sizeof(pwd->pw_uid));
2587                 if (!WBC_ERROR_IS_OK(wbc_status)) {
2588                         goto out;
2589                 }
2590
2591                 wbc_status = wbcLogoffUserEx(&logoff, &error);
2592                 retval = wbc_auth_error_to_pam_error(ctx, error, wbc_status,
2593                                                      user, "wbcLogoffUser");
2594                 wbcFreeMemory(error);
2595                 wbcFreeMemory(logoff.blobs);
2596
2597                 if (!WBC_ERROR_IS_OK(wbc_status)) {
2598                         _pam_log(ctx, LOG_INFO,
2599                                  "failed to logoff user %s: %s\n",
2600                                          user, wbcErrorString(wbc_status));
2601                 }
2602         }
2603
2604 out:
2605         if (logoff.blobs) {
2606                 wbcFreeMemory(logoff.blobs);
2607         }
2608
2609         _PAM_LOG_FUNCTION_LEAVE("pam_sm_close_session", ctx, retval);
2610
2611         TALLOC_FREE(ctx);
2612
2613         return retval;
2614 }
2615
2616 /**
2617  * evaluate whether we need to re-authenticate with kerberos after a
2618  * password change
2619  *
2620  * @param ctx PAM winbind context.
2621  * @param user The username
2622  *
2623  * @return boolean Returns true if required, false if not.
2624  */
2625
2626 static bool _pam_require_krb5_auth_after_chauthtok(struct pwb_context *ctx,
2627                                                    const char *user)
2628 {
2629
2630         /* Make sure that we only do this if a) the chauthtok got initiated
2631          * during a logon attempt (authenticate->acct_mgmt->chauthtok) b) any
2632          * later password change via the "passwd" command if done by the user
2633          * itself
2634          * NB. If we login from gdm or xdm and the password expires,
2635          * we change the password, but there is no memory cache.
2636          * Thus, even for passthrough login, we should do the
2637          * authentication again to update memory cache.
2638          * --- BoYang
2639          * */
2640
2641         char *new_authtok_reqd_during_auth = NULL;
2642         struct passwd *pwd = NULL;
2643
2644         _pam_get_data(ctx->pamh, PAM_WINBIND_NEW_AUTHTOK_REQD_DURING_AUTH,
2645                       &new_authtok_reqd_during_auth);
2646         pam_set_data(ctx->pamh, PAM_WINBIND_NEW_AUTHTOK_REQD_DURING_AUTH,
2647                      NULL, NULL);
2648
2649         if (new_authtok_reqd_during_auth) {
2650                 return true;
2651         }
2652
2653         pwd = getpwnam(user);
2654         if (!pwd) {
2655                 return false;
2656         }
2657
2658         if (getuid() == pwd->pw_uid) {
2659                 return true;
2660         }
2661
2662         return false;
2663 }
2664
2665
2666 PAM_EXTERN
2667 int pam_sm_chauthtok(pam_handle_t * pamh, int flags,
2668                      int argc, const char **argv)
2669 {
2670         unsigned int lctrl;
2671         int ret;
2672         bool cached_login = false;
2673
2674         /* <DO NOT free() THESE> */
2675         const char *user;
2676         char *pass_old, *pass_new;
2677         /* </DO NOT free() THESE> */
2678
2679         char *Announce;
2680
2681         int retry = 0;
2682         char *username_ret = NULL;
2683         struct wbcAuthErrorInfo *error = NULL;
2684         struct pwb_context *ctx = NULL;
2685
2686         ret = _pam_winbind_init_context(pamh, flags, argc, argv, &ctx);
2687         if (ret) {
2688                 goto out;
2689         }
2690
2691         _PAM_LOG_FUNCTION_ENTER("pam_sm_chauthtok", ctx);
2692
2693         cached_login = (ctx->ctrl & WINBIND_CACHED_LOGIN);
2694
2695         /* clearing offline bit for auth */
2696         ctx->ctrl &= ~WINBIND_CACHED_LOGIN;
2697
2698         /*
2699          * First get the name of a user
2700          */
2701         ret = pam_get_user(pamh, &user, "Username: ");
2702         if (ret) {
2703                 _pam_log(ctx, LOG_ERR,
2704                          "password - could not identify user");
2705                 goto out;
2706         }
2707
2708         if (user == NULL) {
2709                 _pam_log(ctx, LOG_ERR, "username was NULL!");
2710                 ret = PAM_USER_UNKNOWN;
2711                 goto out;
2712         }
2713
2714         _pam_log_debug(ctx, LOG_DEBUG, "username [%s] obtained", user);
2715
2716         /* check if this is really a user in winbindd, not only in NSS */
2717         ret = valid_user(ctx, user);
2718         switch (ret) {
2719                 case 1:
2720                         ret = PAM_USER_UNKNOWN;
2721                         goto out;
2722                 case -1:
2723                         ret = PAM_SYSTEM_ERR;
2724                         goto out;
2725                 default:
2726                         break;
2727         }
2728
2729         /*
2730          * obtain and verify the current password (OLDAUTHTOK) for
2731          * the user.
2732          */
2733
2734         if (flags & PAM_PRELIM_CHECK) {
2735                 time_t pwdlastset_prelim = 0;
2736
2737                 /* instruct user what is happening */
2738
2739 #define greeting "Changing password for"
2740                 Announce = talloc_asprintf(ctx, "%s %s", greeting, user);
2741                 if (!Announce) {
2742                         _pam_log(ctx, LOG_CRIT,
2743                                  "password - out of memory");
2744                         ret = PAM_BUF_ERR;
2745                         goto out;
2746                 }
2747 #undef greeting
2748
2749                 lctrl = ctx->ctrl | WINBIND__OLD_PASSWORD;
2750                 ret = _winbind_read_password(ctx, lctrl,
2751                                                 Announce,
2752                                                 "(current) NT password: ",
2753                                                 NULL,
2754                                                 (const char **) &pass_old);
2755                 TALLOC_FREE(Announce);
2756                 if (ret != PAM_SUCCESS) {
2757                         _pam_log(ctx, LOG_NOTICE,
2758                                  "password - (old) token not obtained");
2759                         goto out;
2760                 }
2761
2762                 /* verify that this is the password for this user */
2763
2764                 ret = winbind_auth_request(ctx, user, pass_old,
2765                                            NULL, NULL, 0,
2766                                            &error, NULL, NULL,
2767                                            &pwdlastset_prelim, NULL);
2768
2769                 if (ret != PAM_ACCT_EXPIRED &&
2770                     ret != PAM_AUTHTOK_EXPIRED &&
2771                     ret != PAM_NEW_AUTHTOK_REQD &&
2772                     ret != PAM_SUCCESS) {
2773                         pass_old = NULL;
2774                         goto out;
2775                 }
2776
2777                 pam_set_data(pamh, PAM_WINBIND_PWD_LAST_SET,
2778                              (void *)pwdlastset_prelim, NULL);
2779
2780                 ret = pam_set_item(pamh, PAM_OLDAUTHTOK,
2781                                    (const void *) pass_old);
2782                 pass_old = NULL;
2783                 if (ret != PAM_SUCCESS) {
2784                         _pam_log(ctx, LOG_CRIT,
2785                                  "failed to set PAM_OLDAUTHTOK");
2786                 }
2787         } else if (flags & PAM_UPDATE_AUTHTOK) {
2788
2789                 time_t pwdlastset_update = 0;
2790
2791                 /*
2792                  * obtain the proposed password
2793                  */
2794
2795                 /*
2796                  * get the old token back.
2797                  */
2798
2799                 ret = _pam_get_item(pamh, PAM_OLDAUTHTOK, &pass_old);
2800
2801                 if (ret != PAM_SUCCESS) {
2802                         _pam_log(ctx, LOG_NOTICE,
2803                                  "user not authenticated");
2804                         goto out;
2805                 }
2806
2807                 lctrl = ctx->ctrl & ~WINBIND_TRY_FIRST_PASS_ARG;
2808
2809                 if (on(WINBIND_USE_AUTHTOK_ARG, lctrl)) {
2810                         lctrl |= WINBIND_USE_FIRST_PASS_ARG;
2811                 }
2812                 retry = 0;
2813                 ret = PAM_AUTHTOK_ERR;
2814                 while ((ret != PAM_SUCCESS) && (retry++ < MAX_PASSWD_TRIES)) {
2815                         /*
2816                          * use_authtok is to force the use of a previously entered
2817                          * password -- needed for pluggable password strength checking
2818                          */
2819
2820                         ret = _winbind_read_password(ctx, lctrl,
2821                                                      NULL,
2822                                                      "Enter new NT password: ",
2823                                                      "Retype new NT password: ",
2824                                                      (const char **)&pass_new);
2825
2826                         if (ret != PAM_SUCCESS) {
2827                                 _pam_log_debug(ctx, LOG_ALERT,
2828                                                "password - "
2829                                                "new password not obtained");
2830                                 pass_old = NULL;/* tidy up */
2831                                 goto out;
2832                         }
2833
2834                         /*
2835                          * At this point we know who the user is and what they
2836                          * propose as their new password. Verify that the new
2837                          * password is acceptable.
2838                          */
2839
2840                         if (pass_new[0] == '\0') {/* "\0" password = NULL */
2841                                 pass_new = NULL;
2842                         }
2843                 }
2844
2845                 /*
2846                  * By reaching here we have approved the passwords and must now
2847                  * rebuild the password database file.
2848                  */
2849                 _pam_get_data(pamh, PAM_WINBIND_PWD_LAST_SET,
2850                               &pwdlastset_update);
2851
2852                 /*
2853                  * if cached creds were enabled, make sure to set the
2854                  * WINBIND_CACHED_LOGIN bit here in order to have winbindd
2855                  * update the cached creds storage - gd
2856                  */
2857                 if (cached_login) {
2858                         ctx->ctrl |= WINBIND_CACHED_LOGIN;
2859                 }
2860
2861                 ret = winbind_chauthtok_request(ctx, user, pass_old,
2862                                                 pass_new, pwdlastset_update);
2863                 if (ret) {
2864                         _pam_overwrite(pass_new);
2865                         _pam_overwrite(pass_old);
2866                         pass_old = pass_new = NULL;
2867                         goto out;
2868                 }
2869
2870                 if (_pam_require_krb5_auth_after_chauthtok(ctx, user)) {
2871
2872                         const char *member = NULL;
2873                         const char *cctype = NULL;
2874                         int warn_pwd_expire;
2875                         struct wbcLogonUserInfo *info = NULL;
2876                         struct wbcUserPasswordPolicyInfo *policy = NULL;
2877
2878                         member = get_member_from_config(ctx);
2879                         cctype = get_krb5_cc_type_from_config(ctx);
2880                         warn_pwd_expire = get_warn_pwd_expire_from_config(ctx);
2881
2882                         /* Keep WINBIND_CACHED_LOGIN bit for
2883                          * authentication after changing the password.
2884                          * This will update the cached credentials in case
2885                          * that winbindd_dual_pam_chauthtok() fails
2886                          * to update them.
2887                          * --- BoYang
2888                          * */
2889
2890                         ret = winbind_auth_request(ctx, user, pass_new,
2891                                                    member, cctype, 0,
2892                                                    &error, &info, &policy,
2893                                                    NULL, &username_ret);
2894                         _pam_overwrite(pass_new);
2895                         _pam_overwrite(pass_old);
2896                         pass_old = pass_new = NULL;
2897
2898                         if (ret == PAM_SUCCESS) {
2899
2900                                 struct wbcAuthUserInfo *user_info = NULL;
2901
2902                                 if (info && info->info) {
2903                                         user_info = info->info;
2904                                 }
2905
2906                                 /* warn a user if the password is about to
2907                                  * expire soon */
2908                                 _pam_warn_password_expiry(ctx, user_info, policy,
2909                                                           warn_pwd_expire,
2910                                                           NULL);
2911
2912                                 /* set some info3 info for other modules in the
2913                                  * stack */
2914                                 _pam_set_data_info3(ctx, user_info);
2915
2916                                 /* put krb5ccname into env */
2917                                 _pam_setup_krb5_env(ctx, info);
2918
2919                                 if (username_ret) {
2920                                         pam_set_item(pamh, PAM_USER,
2921                                                      username_ret);
2922                                         _pam_log_debug(ctx, LOG_INFO,
2923                                                        "Returned user was '%s'",
2924                                                        username_ret);
2925                                         free(username_ret);
2926                                 }
2927
2928                                 wbcFreeMemory(info);
2929                                 wbcFreeMemory(policy);
2930                         }
2931
2932                         goto out;
2933                 }
2934         } else {
2935                 ret = PAM_SERVICE_ERR;
2936         }
2937
2938 out:
2939         {
2940                 /* Deal with offline errors. */
2941                 int i;
2942                 const char *codes[] = {
2943                         "NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND",
2944                         "NT_STATUS_NO_LOGON_SERVERS",
2945                         "NT_STATUS_ACCESS_DENIED"
2946                 };
2947
2948                 for (i=0; i<ARRAY_SIZE(codes); i++) {
2949                         int _ret;
2950                         if (_pam_check_remark_auth_err(ctx, error, codes[i], &_ret)) {
2951                                 break;
2952                         }
2953                 }
2954         }
2955
2956         wbcFreeMemory(error);
2957
2958         _PAM_LOG_FUNCTION_LEAVE("pam_sm_chauthtok", ctx, ret);
2959
2960         TALLOC_FREE(ctx);
2961
2962         return ret;
2963 }
2964
2965 #ifdef PAM_STATIC
2966
2967 /* static module data */
2968
2969 struct pam_module _pam_winbind_modstruct = {
2970         MODULE_NAME,
2971         pam_sm_authenticate,
2972         pam_sm_setcred,
2973         pam_sm_acct_mgmt,
2974         pam_sm_open_session,
2975         pam_sm_close_session,
2976         pam_sm_chauthtok
2977 };
2978
2979 #endif
2980
2981 /*
2982  * Copyright (c) Andrew Tridgell  <tridge@samba.org>   2000
2983  * Copyright (c) Tim Potter       <tpot@samba.org>     2000
2984  * Copyright (c) Andrew Bartlettt <abartlet@samba.org> 2002
2985  * Copyright (c) Guenther Deschner <gd@samba.org>      2005-2008
2986  * Copyright (c) Jan Rêkorajski 1999.
2987  * Copyright (c) Andrew G. Morgan 1996-8.
2988  * Copyright (c) Alex O. Yuriev, 1996.
2989  * Copyright (c) Cristian Gafton 1996.
2990  * Copyright (C) Elliot Lee <sopwith@redhat.com> 1996, Red Hat Software.
2991  *
2992  * Redistribution and use in source and binary forms, with or without
2993  * modification, are permitted provided that the following conditions
2994  * are met:
2995  * 1. Redistributions of source code must retain the above copyright
2996  *    notice, and the entire permission notice in its entirety,
2997  *    including the disclaimer of warranties.
2998  * 2. Redistributions in binary form must reproduce the above copyright
2999  *    notice, this list of conditions and the following disclaimer in the
3000  *    documentation and/or other materials provided with the distribution.
3001  * 3. The name of the author may not be used to endorse or promote
3002  *    products derived from this software without specific prior
3003  *    written permission.
3004  *
3005  * ALTERNATIVELY, this product may be distributed under the terms of
3006  * the GNU Public License, in which case the provisions of the GPL are
3007  * required INSTEAD OF the above restrictions.  (This clause is
3008  * necessary due to a potential bad interaction between the GPL and
3009  * the restrictions contained in a BSD-style copyright.)
3010  *
3011  * THIS SOFTWARE IS PROVIDED `AS IS'' AND ANY EXPRESS OR IMPLIED
3012  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
3013  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
3014  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
3015  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
3016  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
3017  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3018  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
3019  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
3020  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
3021  * OF THE POSSIBILITY OF SUCH DAMAGE.
3022  */