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