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