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