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