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