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