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