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