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