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