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