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