Merge branch 'selftest' of git://git.samba.org/jelmer/samba
[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         wbc_status = wbcAddNamedBlob(&logon.num_blobs,
1619                                      &logon.blobs,
1620                                      "krb5_cc_type",
1621                                      0,
1622                                      (uint8_t *)cctype,
1623                                      strlen(cctype)+1);
1624         if (!WBC_ERROR_IS_OK(wbc_status)) {
1625                 goto done;
1626         }
1627
1628         wbc_status = wbcAddNamedBlob(&logon.num_blobs,
1629                                      &logon.blobs,
1630                                      "flags",
1631                                      0,
1632                                      (uint8_t *)&flags,
1633                                      sizeof(flags));
1634         if (!WBC_ERROR_IS_OK(wbc_status)) {
1635                 goto done;
1636         }
1637
1638         wbc_status = wbcAddNamedBlob(&logon.num_blobs,
1639                                      &logon.blobs,
1640                                      "user_uid",
1641                                      0,
1642                                      (uint8_t *)&user_uid,
1643                                      sizeof(user_uid));
1644         if (!WBC_ERROR_IS_OK(wbc_status)) {
1645                 goto done;
1646         }
1647
1648         wbc_status = wbcAddNamedBlob(&logon.num_blobs,
1649                                      &logon.blobs,
1650                                      "membership_of",
1651                                      0,
1652                                      (uint8_t *)membership_of,
1653                                      sizeof(membership_of));
1654         if (!WBC_ERROR_IS_OK(wbc_status)) {
1655                 goto done;
1656         }
1657
1658         wbc_status = wbcLogonUser(&logon, &info, &error, &policy);
1659         ret = wbc_auth_error_to_pam_error(ctx, error, wbc_status,
1660                                           user, "wbcLogonUser");
1661         wbcFreeMemory(logon.blobs);
1662         logon.blobs = NULL;
1663
1664         if (info && info->info) {
1665                 user_info = info->info;
1666         }
1667
1668         if (pwd_last_set && user_info) {
1669                 *pwd_last_set = user_info->pass_last_set_time;
1670         }
1671
1672         if (p_info && info) {
1673                 *p_info = info;
1674         }
1675
1676         if (p_policy && policy) {
1677                 *p_policy = policy;
1678         }
1679
1680         if (p_error && error) {
1681                 /* We want to process the error in the caller. */
1682                 *p_error = error;
1683                 return ret;
1684         }
1685
1686         for (i=0; i<ARRAY_SIZE(codes); i++) {
1687                 int _ret = ret;
1688                 if (_pam_check_remark_auth_err(ctx, error, codes[i], &_ret)) {
1689                         ret = _ret;
1690                         goto done;
1691                 }
1692         }
1693
1694         if ((ret == PAM_SUCCESS) && user_info && policy && info) {
1695
1696                 bool already_expired = false;
1697
1698                 /* warn a user if the password is about to expire soon */
1699                 _pam_warn_password_expiry(ctx, user_info, policy,
1700                                           warn_pwd_expire,
1701                                           &already_expired);
1702
1703                 if (already_expired == true) {
1704
1705                         SMB_TIME_T last_set = user_info->pass_last_set_time;
1706
1707                         _pam_log_debug(ctx, LOG_DEBUG,
1708                                        "Password has expired "
1709                                        "(Password was last set: %lld, "
1710                                        "the policy says it should expire here "
1711                                        "%lld (now it's: %lu))\n",
1712                                        (long long int)last_set,
1713                                        (long long int)last_set +
1714                                        policy->expire,
1715                                        time(NULL));
1716
1717                         return PAM_AUTHTOK_EXPIRED;
1718                 }
1719
1720                 /* inform about logon type */
1721                 _pam_warn_logon_type(ctx, user, user_info->user_flags);
1722
1723                 /* inform about krb5 failures */
1724                 _pam_warn_krb5_failure(ctx, user, user_info->user_flags);
1725
1726                 /* set some info3 info for other modules in the stack */
1727                 _pam_set_data_info3(ctx, user_info);
1728
1729                 /* put krb5ccname into env */
1730                 _pam_setup_krb5_env(ctx, info);
1731
1732                 /* If winbindd returned a username, return the pointer to it
1733                  * here. */
1734                 _pam_setup_unix_username(ctx, user_ret, info);
1735         }
1736
1737  done:
1738         if (logon.blobs) {
1739                 wbcFreeMemory(logon.blobs);
1740         }
1741         if (info && info->blobs) {
1742                 wbcFreeMemory(info->blobs);
1743         }
1744         if (error && !p_error) {
1745                 wbcFreeMemory(error);
1746         }
1747         if (info && !p_info) {
1748                 wbcFreeMemory(info);
1749         }
1750         if (policy && !p_policy) {
1751                 wbcFreeMemory(policy);
1752         }
1753
1754         return ret;
1755 }
1756
1757 /* talk to winbindd */
1758 static int winbind_chauthtok_request(struct pwb_context *ctx,
1759                                      const char *user,
1760                                      const char *oldpass,
1761                                      const char *newpass,
1762                                      time_t pwd_last_set)
1763 {
1764         wbcErr wbc_status;
1765         struct wbcChangePasswordParams params;
1766         struct wbcAuthErrorInfo *error = NULL;
1767         struct wbcUserPasswordPolicyInfo *policy = NULL;
1768         enum wbcPasswordChangeRejectReason reject_reason = -1;
1769         uint32_t flags = 0;
1770
1771         int i;
1772         const char *codes[] = {
1773                 "NT_STATUS_BACKUP_CONTROLLER",
1774                 "NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND",
1775                 "NT_STATUS_NO_LOGON_SERVERS",
1776                 "NT_STATUS_ACCESS_DENIED",
1777                 "NT_STATUS_PWD_TOO_SHORT", /* TODO: tell the min pwd length ? */
1778                 "NT_STATUS_PWD_TOO_RECENT", /* TODO: tell the minage ? */
1779                 "NT_STATUS_PWD_HISTORY_CONFLICT" /* TODO: tell the history length ? */
1780         };
1781         int ret = PAM_AUTH_ERR;
1782
1783         ZERO_STRUCT(params);
1784
1785         if (ctx->ctrl & WINBIND_KRB5_AUTH) {
1786                 flags |= WBFLAG_PAM_KRB5 |
1787                          WBFLAG_PAM_CONTACT_TRUSTDOM;
1788         }
1789
1790         if (ctx->ctrl & WINBIND_CACHED_LOGIN) {
1791                 flags |= WBFLAG_PAM_CACHED_LOGIN;
1792         }
1793
1794         params.account_name             = user;
1795         params.level                    = WBC_AUTH_USER_LEVEL_PLAIN;
1796         params.old_password.plaintext   = oldpass;
1797         params.new_password.plaintext   = newpass;
1798         params.flags                    = flags;
1799
1800         wbc_status = wbcChangeUserPasswordEx(&params, &error, &reject_reason, &policy);
1801         ret = wbc_auth_error_to_pam_error(ctx, error, wbc_status,
1802                                           user, "wbcChangeUserPasswordEx");
1803
1804         if (WBC_ERROR_IS_OK(wbc_status)) {
1805                 _pam_log(ctx, LOG_NOTICE,
1806                          "user '%s' password changed", user);
1807                 return PAM_SUCCESS;
1808         }
1809
1810         if (!error) {
1811                 wbcFreeMemory(policy);
1812                 return ret;
1813         }
1814
1815         for (i=0; i<ARRAY_SIZE(codes); i++) {
1816                 int _ret = ret;
1817                 if (_pam_check_remark_auth_err(ctx, error, codes[i], &_ret)) {
1818                         ret = _ret;
1819                         goto done;
1820                 }
1821         }
1822
1823         if (!strcasecmp(error->nt_string,
1824                         "NT_STATUS_PASSWORD_RESTRICTION")) {
1825
1826                 char *pwd_restriction_string = NULL;
1827                 SMB_TIME_T min_pwd_age = 0;
1828
1829                 if (policy) {
1830                         min_pwd_age     = policy->min_passwordage;
1831                 }
1832
1833                 /* FIXME: avoid to send multiple PAM messages after another */
1834                 switch (reject_reason) {
1835                         case -1:
1836                                 break;
1837                         case WBC_PWD_CHANGE_REJECT_OTHER:
1838                                 if ((min_pwd_age > 0) &&
1839                                     (pwd_last_set + min_pwd_age > time(NULL))) {
1840                                         PAM_WB_REMARK_DIRECT(ctx,
1841                                              "NT_STATUS_PWD_TOO_RECENT");
1842                                 }
1843                                 break;
1844                         case WBC_PWD_CHANGE_REJECT_TOO_SHORT:
1845                                 PAM_WB_REMARK_DIRECT(ctx,
1846                                         "NT_STATUS_PWD_TOO_SHORT");
1847                                 break;
1848                         case WBC_PWD_CHANGE_REJECT_IN_HISTORY:
1849                                 PAM_WB_REMARK_DIRECT(ctx,
1850                                         "NT_STATUS_PWD_HISTORY_CONFLICT");
1851                                 break;
1852                         case WBC_PWD_CHANGE_REJECT_COMPLEXITY:
1853                                 _make_remark(ctx, PAM_ERROR_MSG,
1854                                              "Password does not meet "
1855                                              "complexity requirements");
1856                                 break;
1857                         default:
1858                                 _pam_log_debug(ctx, LOG_DEBUG,
1859                                                "unknown password change "
1860                                                "reject reason: %d",
1861                                                reject_reason);
1862                                 break;
1863                 }
1864
1865                 pwd_restriction_string =
1866                         _pam_compose_pwd_restriction_string(ctx, policy);
1867                 if (pwd_restriction_string) {
1868                         _make_remark(ctx, PAM_ERROR_MSG,
1869                                      pwd_restriction_string);
1870                         TALLOC_FREE(pwd_restriction_string);
1871                 }
1872         }
1873  done:
1874         wbcFreeMemory(error);
1875         wbcFreeMemory(policy);
1876
1877         return ret;
1878 }
1879
1880 /*
1881  * Checks if a user has an account
1882  *
1883  * return values:
1884  *       1  = User not found
1885  *       0  = OK
1886  *      -1  = System error
1887  */
1888 static int valid_user(struct pwb_context *ctx,
1889                       const char *user)
1890 {
1891         /* check not only if the user is available over NSS calls, also make
1892          * sure it's really a winbind user, this is important when stacking PAM
1893          * modules in the 'account' or 'password' facility. */
1894
1895         wbcErr wbc_status;
1896         struct passwd *pwd = NULL;
1897         struct passwd *wb_pwd = NULL;
1898
1899         pwd = getpwnam(user);
1900         if (pwd == NULL) {
1901                 return 1;
1902         }
1903
1904         wbc_status = wbcGetpwnam(user, &wb_pwd);
1905         wbcFreeMemory(wb_pwd);
1906         if (!WBC_ERROR_IS_OK(wbc_status)) {
1907                 _pam_log(ctx, LOG_DEBUG, "valid_user: wbcGetpwnam gave %s\n",
1908                         wbcErrorString(wbc_status));
1909         }
1910
1911         switch (wbc_status) {
1912                 case WBC_ERR_UNKNOWN_USER:
1913                         return 1;
1914                 case WBC_ERR_SUCCESS:
1915                         return 0;
1916                 default:
1917                         break;
1918         }
1919         return -1;
1920 }
1921
1922 static char *_pam_delete(register char *xx)
1923 {
1924         _pam_overwrite(xx);
1925         _pam_drop(xx);
1926         return NULL;
1927 }
1928
1929 /*
1930  * obtain a password from the user
1931  */
1932
1933 static int _winbind_read_password(struct pwb_context *ctx,
1934                                   unsigned int ctrl,
1935                                   const char *comment,
1936                                   const char *prompt1,
1937                                   const char *prompt2,
1938                                   const char **pass)
1939 {
1940         int authtok_flag;
1941         int retval;
1942         const char *item;
1943         char *token;
1944
1945         _pam_log(ctx, LOG_DEBUG, "getting password (0x%08x)", ctrl);
1946
1947         /*
1948          * make sure nothing inappropriate gets returned
1949          */
1950
1951         *pass = token = NULL;
1952
1953         /*
1954          * which authentication token are we getting?
1955          */
1956
1957         if (on(WINBIND__OLD_PASSWORD, ctrl)) {
1958                 authtok_flag = PAM_OLDAUTHTOK;
1959         } else {
1960                 authtok_flag = PAM_AUTHTOK;
1961         }
1962
1963         /*
1964          * should we obtain the password from a PAM item ?
1965          */
1966
1967         if (on(WINBIND_TRY_FIRST_PASS_ARG, ctrl) ||
1968             on(WINBIND_USE_FIRST_PASS_ARG, ctrl)) {
1969                 retval = _pam_get_item(ctx->pamh, authtok_flag, &item);
1970                 if (retval != PAM_SUCCESS) {
1971                         /* very strange. */
1972                         _pam_log(ctx, LOG_ALERT,
1973                                  "pam_get_item returned error "
1974                                  "to unix-read-password");
1975                         return retval;
1976                 } else if (item != NULL) {      /* we have a password! */
1977                         *pass = item;
1978                         item = NULL;
1979                         _pam_log(ctx, LOG_DEBUG,
1980                                  "pam_get_item returned a password");
1981                         return PAM_SUCCESS;
1982                 } else if (on(WINBIND_USE_FIRST_PASS_ARG, ctrl)) {
1983                         return PAM_AUTHTOK_RECOVER_ERR; /* didn't work */
1984                 } else if (on(WINBIND_USE_AUTHTOK_ARG, ctrl)
1985                            && off(WINBIND__OLD_PASSWORD, ctrl)) {
1986                         return PAM_AUTHTOK_RECOVER_ERR;
1987                 }
1988         }
1989         /*
1990          * getting here implies we will have to get the password from the
1991          * user directly.
1992          */
1993
1994         {
1995                 struct pam_message msg[3], *pmsg[3];
1996                 struct pam_response *resp;
1997                 int i, replies;
1998
1999                 /* prepare to converse */
2000
2001                 if (comment != NULL && off(ctrl, WINBIND_SILENT)) {
2002                         pmsg[0] = &msg[0];
2003                         msg[0].msg_style = PAM_TEXT_INFO;
2004                         msg[0].msg = discard_const_p(char, comment);
2005                         i = 1;
2006                 } else {
2007                         i = 0;
2008                 }
2009
2010                 pmsg[i] = &msg[i];
2011                 msg[i].msg_style = PAM_PROMPT_ECHO_OFF;
2012                 msg[i++].msg = discard_const_p(char, prompt1);
2013                 replies = 1;
2014
2015                 if (prompt2 != NULL) {
2016                         pmsg[i] = &msg[i];
2017                         msg[i].msg_style = PAM_PROMPT_ECHO_OFF;
2018                         msg[i++].msg = discard_const_p(char, prompt2);
2019                         ++replies;
2020                 }
2021                 /* so call the conversation expecting i responses */
2022                 resp = NULL;
2023                 retval = converse(ctx->pamh, i, pmsg, &resp);
2024                 if (resp == NULL) {
2025                         if (retval == PAM_SUCCESS) {
2026                                 retval = PAM_AUTHTOK_RECOVER_ERR;
2027                         }
2028                         goto done;
2029                 }
2030                 if (retval != PAM_SUCCESS) {
2031                         _pam_drop_reply(resp, i);
2032                         goto done;
2033                 }
2034
2035                 /* interpret the response */
2036
2037                 token = x_strdup(resp[i - replies].resp);
2038                 if (!token) {
2039                         _pam_log(ctx, LOG_NOTICE,
2040                                  "could not recover "
2041                                  "authentication token");
2042                         retval = PAM_AUTHTOK_RECOVER_ERR;
2043                         goto done;
2044                 }
2045
2046                 if (replies == 2) {
2047                         /* verify that password entered correctly */
2048                         if (!resp[i - 1].resp ||
2049                             strcmp(token, resp[i - 1].resp)) {
2050                                 _pam_delete(token);     /* mistyped */
2051                                 retval = PAM_AUTHTOK_RECOVER_ERR;
2052                                 _make_remark(ctx, PAM_ERROR_MSG,
2053                                              MISTYPED_PASS);
2054                         }
2055                 }
2056
2057                 /*
2058                  * tidy up the conversation (resp_retcode) is ignored
2059                  * -- what is it for anyway? AGM
2060                  */
2061                 _pam_drop_reply(resp, i);
2062         }
2063
2064  done:
2065         if (retval != PAM_SUCCESS) {
2066                 _pam_log_debug(ctx, LOG_DEBUG,
2067                                "unable to obtain a password");
2068                 return retval;
2069         }
2070         /* 'token' is the entered password */
2071
2072         /* we store this password as an item */
2073
2074         retval = pam_set_item(ctx->pamh, authtok_flag, token);
2075         _pam_delete(token);     /* clean it up */
2076         if (retval != PAM_SUCCESS ||
2077             (retval = _pam_get_item(ctx->pamh, authtok_flag, &item)) != PAM_SUCCESS) {
2078
2079                 _pam_log(ctx, LOG_CRIT, "error manipulating password");
2080                 return retval;
2081
2082         }
2083
2084         *pass = item;
2085         item = NULL;            /* break link to password */
2086
2087         return PAM_SUCCESS;
2088 }
2089
2090 static const char *get_conf_item_string(struct pwb_context *ctx,
2091                                         const char *item,
2092                                         int config_flag)
2093 {
2094         int i = 0;
2095         const char *parm_opt = NULL;
2096
2097         if (!(ctx->ctrl & config_flag)) {
2098                 goto out;
2099         }
2100
2101         /* let the pam opt take precedence over the pam_winbind.conf option */
2102         for (i=0; i<ctx->argc; i++) {
2103
2104                 if ((strncmp(ctx->argv[i], item, strlen(item)) == 0)) {
2105                         char *p;
2106
2107                         if ((p = strchr(ctx->argv[i], '=')) == NULL) {
2108                                 _pam_log(ctx, LOG_INFO,
2109                                          "no \"=\" delimiter for \"%s\" found\n",
2110                                          item);
2111                                 goto out;
2112                         }
2113                         _pam_log_debug(ctx, LOG_INFO,
2114                                        "PAM config: %s '%s'\n", item, p+1);
2115                         return p + 1;
2116                 }
2117         }
2118
2119         if (ctx->dict) {
2120                 char *key = NULL;
2121
2122                 key = talloc_asprintf(ctx, "global:%s", item);
2123                 if (!key) {
2124                         goto out;
2125                 }
2126
2127                 parm_opt = iniparser_getstr(ctx->dict, key);
2128                 TALLOC_FREE(key);
2129
2130                 _pam_log_debug(ctx, LOG_INFO, "CONFIG file: %s '%s'\n",
2131                                item, parm_opt);
2132         }
2133 out:
2134         return parm_opt;
2135 }
2136
2137 static int get_config_item_int(struct pwb_context *ctx,
2138                                const char *item,
2139                                int config_flag)
2140 {
2141         int i, parm_opt = -1;
2142
2143         if (!(ctx->ctrl & config_flag)) {
2144                 goto out;
2145         }
2146
2147         /* let the pam opt take precedence over the pam_winbind.conf option */
2148         for (i = 0; i < ctx->argc; i++) {
2149
2150                 if ((strncmp(ctx->argv[i], item, strlen(item)) == 0)) {
2151                         char *p;
2152
2153                         if ((p = strchr(ctx->argv[i], '=')) == NULL) {
2154                                 _pam_log(ctx, LOG_INFO,
2155                                          "no \"=\" delimiter for \"%s\" found\n",
2156                                          item);
2157                                 goto out;
2158                         }
2159                         parm_opt = atoi(p + 1);
2160                         _pam_log_debug(ctx, LOG_INFO,
2161                                        "PAM config: %s '%d'\n",
2162                                        item, parm_opt);
2163                         return parm_opt;
2164                 }
2165         }
2166
2167         if (ctx->dict) {
2168                 char *key = NULL;
2169
2170                 key = talloc_asprintf(ctx, "global:%s", item);
2171                 if (!key) {
2172                         goto out;
2173                 }
2174
2175                 parm_opt = iniparser_getint(ctx->dict, key, -1);
2176                 TALLOC_FREE(key);
2177
2178                 _pam_log_debug(ctx, LOG_INFO,
2179                                "CONFIG file: %s '%d'\n",
2180                                item, parm_opt);
2181         }
2182 out:
2183         return parm_opt;
2184 }
2185
2186 static const char *get_krb5_cc_type_from_config(struct pwb_context *ctx)
2187 {
2188         return get_conf_item_string(ctx, "krb5_ccache_type",
2189                                     WINBIND_KRB5_CCACHE_TYPE);
2190 }
2191
2192 static const char *get_member_from_config(struct pwb_context *ctx)
2193 {
2194         const char *ret = NULL;
2195         ret = get_conf_item_string(ctx, "require_membership_of",
2196                                    WINBIND_REQUIRED_MEMBERSHIP);
2197         if (ret) {
2198                 return ret;
2199         }
2200         return get_conf_item_string(ctx, "require-membership-of",
2201                                     WINBIND_REQUIRED_MEMBERSHIP);
2202 }
2203
2204 static int get_warn_pwd_expire_from_config(struct pwb_context *ctx)
2205 {
2206         int ret;
2207         ret = get_config_item_int(ctx, "warn_pwd_expire",
2208                                   WINBIND_WARN_PWD_EXPIRE);
2209         /* no or broken setting */
2210         if (ret <= 0) {
2211                 return DEFAULT_DAYS_TO_WARN_BEFORE_PWD_EXPIRES;
2212         }
2213         return ret;
2214 }
2215
2216 /**
2217  * Retrieve the winbind separator.
2218  *
2219  * @param ctx PAM winbind context.
2220  *
2221  * @return string separator character. NULL on failure.
2222  */
2223
2224 static char winbind_get_separator(struct pwb_context *ctx)
2225 {
2226         wbcErr wbc_status;
2227         static struct wbcInterfaceDetails *details = NULL;
2228
2229         wbc_status = wbcInterfaceDetails(&details);
2230         if (!WBC_ERROR_IS_OK(wbc_status)) {
2231                 _pam_log(ctx, LOG_ERR,
2232                          "Could not retrieve winbind interface details: %s",
2233                          wbcErrorString(wbc_status));
2234                 return '\0';
2235         }
2236
2237         if (!details) {
2238                 return '\0';
2239         }
2240
2241         return details->winbind_separator;
2242 }
2243
2244
2245 /**
2246  * Convert a upn to a name.
2247  *
2248  * @param ctx PAM winbind context.
2249  * @param upn  USer UPN to be trabslated.
2250  *
2251  * @return converted name. NULL pointer on failure. Caller needs to free.
2252  */
2253
2254 static char* winbind_upn_to_username(struct pwb_context *ctx,
2255                                      const char *upn)
2256 {
2257         char sep;
2258         wbcErr wbc_status = WBC_ERR_UNKNOWN_FAILURE;
2259         struct wbcDomainSid sid;
2260         enum wbcSidType type;
2261         char *domain;
2262         char *name;
2263
2264         /* This cannot work when the winbind separator = @ */
2265
2266         sep = winbind_get_separator(ctx);
2267         if (!sep || sep == '@') {
2268                 return NULL;
2269         }
2270
2271         /* Convert the UPN to a SID */
2272
2273         wbc_status = wbcLookupName("", upn, &sid, &type);
2274         if (!WBC_ERROR_IS_OK(wbc_status)) {
2275                 return NULL;
2276         }
2277
2278         /* Convert the the SID back to the sAMAccountName */
2279
2280         wbc_status = wbcLookupSid(&sid, &domain, &name, &type);
2281         if (!WBC_ERROR_IS_OK(wbc_status)) {
2282                 return NULL;
2283         }
2284
2285         return talloc_asprintf(ctx, "%s\\%s", domain, name);
2286 }
2287
2288 static int _pam_delete_cred(pam_handle_t *pamh, int flags,
2289                          int argc, const char **argv)
2290 {
2291         int retval = PAM_SUCCESS;
2292         struct pwb_context *ctx = NULL;
2293         struct wbcLogoffUserParams logoff;
2294         struct wbcAuthErrorInfo *error = NULL;
2295         const char *user;
2296         wbcErr wbc_status;
2297
2298         retval = _pam_winbind_init_context(pamh, flags, argc, argv, &ctx);
2299         if (retval) {
2300                 goto out;
2301         }
2302
2303         _PAM_LOG_FUNCTION_ENTER("_pam_delete_cred", ctx);
2304
2305         if (ctx->ctrl & WINBIND_KRB5_AUTH) {
2306
2307                 /* destroy the ccache here */
2308
2309                 uint32_t wbc_flags = 0;
2310                 const char *ccname = NULL;
2311                 struct passwd *pwd = NULL;
2312
2313                 retval = pam_get_user(pamh, &user, "Username: ");
2314                 if (retval) {
2315                         _pam_log(ctx, LOG_ERR,
2316                                  "could not identify user");
2317                         goto out;
2318                 }
2319
2320                 if (user == NULL) {
2321                         _pam_log(ctx, LOG_ERR,
2322                                  "username was NULL!");
2323                         retval = PAM_USER_UNKNOWN;
2324                         goto out;
2325                 }
2326
2327                 _pam_log_debug(ctx, LOG_DEBUG,
2328                                "username [%s] obtained", user);
2329
2330                 ccname = pam_getenv(pamh, "KRB5CCNAME");
2331                 if (ccname == NULL) {
2332                         _pam_log_debug(ctx, LOG_DEBUG,
2333                                        "user has no KRB5CCNAME environment");
2334                 }
2335
2336                 pwd = getpwnam(user);
2337                 if (pwd == NULL) {
2338                         retval = PAM_USER_UNKNOWN;
2339                         goto out;
2340                 }
2341
2342                 wbc_flags = WBFLAG_PAM_KRB5 |
2343                         WBFLAG_PAM_CONTACT_TRUSTDOM;
2344
2345                 ZERO_STRUCT(logoff);
2346
2347                 logoff.username         = user;
2348
2349                 wbc_status = wbcAddNamedBlob(&logoff.num_blobs,
2350                                              &logoff.blobs,
2351                                              "ccfilename",
2352                                              0,
2353                                              (uint8_t *)ccname,
2354                                              strlen(ccname)+1);
2355                 if (!WBC_ERROR_IS_OK(wbc_status)) {
2356                         goto out;
2357                 }
2358
2359                 wbc_status = wbcAddNamedBlob(&logoff.num_blobs,
2360                                              &logoff.blobs,
2361                                              "flags",
2362                                              0,
2363                                              (uint8_t *)&wbc_flags,
2364                                              sizeof(wbc_flags));
2365                 if (!WBC_ERROR_IS_OK(wbc_status)) {
2366                         goto out;
2367                 }
2368
2369                 wbc_status = wbcAddNamedBlob(&logoff.num_blobs,
2370                                              &logoff.blobs,
2371                                              "user_uid",
2372                                              0,
2373                                              (uint8_t *)&pwd->pw_uid,
2374                                              sizeof(pwd->pw_uid));
2375                 if (!WBC_ERROR_IS_OK(wbc_status)) {
2376                         goto out;
2377                 }
2378
2379                 wbc_status = wbcLogoffUserEx(&logoff, &error);
2380                 retval = wbc_auth_error_to_pam_error(ctx, error, wbc_status,
2381                                                      user, "wbcLogoffUser");
2382                 wbcFreeMemory(error);
2383                 wbcFreeMemory(logoff.blobs);
2384
2385                 if (!WBC_ERROR_IS_OK(wbc_status)) {
2386                         _pam_log(ctx, LOG_INFO,
2387                                  "failed to logoff user %s: %s\n",
2388                                          user, wbcErrorString(wbc_status));
2389                 }
2390         }
2391
2392 out:
2393         if (logoff.blobs) {
2394                 wbcFreeMemory(logoff.blobs);
2395         }
2396
2397         if (!WBC_ERROR_IS_OK(wbc_status)) {
2398                 retval = wbc_auth_error_to_pam_error(ctx, error, wbc_status,
2399                      user, "wbcLogoffUser");
2400         }
2401
2402         /*
2403          * Delete the krb5 ccname variable from the PAM environment
2404          * if it was set by winbind.
2405          */
2406         if (ctx->ctrl & WINBIND_KRB5_AUTH) {
2407                 pam_putenv(pamh, "KRB5CCNAME");
2408         }
2409
2410         _PAM_LOG_FUNCTION_LEAVE("_pam_delete_cred", ctx, retval);
2411
2412         TALLOC_FREE(ctx);
2413
2414         return retval;
2415 }
2416
2417 PAM_EXTERN
2418 int pam_sm_authenticate(pam_handle_t *pamh, int flags,
2419                         int argc, const char **argv)
2420 {
2421         const char *username;
2422         const char *password;
2423         const char *member = NULL;
2424         const char *cctype = NULL;
2425         int warn_pwd_expire;
2426         int retval = PAM_AUTH_ERR;
2427         char *username_ret = NULL;
2428         char *new_authtok_required = NULL;
2429         char *real_username = NULL;
2430         struct pwb_context *ctx = NULL;
2431
2432         retval = _pam_winbind_init_context(pamh, flags, argc, argv, &ctx);
2433         if (retval) {
2434                 goto out;
2435         }
2436
2437         _PAM_LOG_FUNCTION_ENTER("pam_sm_authenticate", ctx);
2438
2439         /* Get the username */
2440         retval = pam_get_user(pamh, &username, NULL);
2441         if ((retval != PAM_SUCCESS) || (!username)) {
2442                 _pam_log_debug(ctx, LOG_DEBUG,
2443                                "can not get the username");
2444                 retval = PAM_SERVICE_ERR;
2445                 goto out;
2446         }
2447
2448
2449 #if defined(AIX)
2450         /* Decode the user name since AIX does not support logn user
2451            names by default.  The name is encoded as _#uid.  */
2452
2453         if (username[0] == '_') {
2454                 uid_t id = atoi(&username[1]);
2455                 struct passwd *pw = NULL;
2456
2457                 if ((id!=0) && ((pw = getpwuid(id)) != NULL)) {
2458                         real_username = strdup(pw->pw_name);
2459                 }
2460         }
2461 #endif
2462
2463         if (!real_username) {
2464                 /* Just making a copy of the username we got from PAM */
2465                 if ((real_username = strdup(username)) == NULL) {
2466                         _pam_log_debug(ctx, LOG_DEBUG,
2467                                        "memory allocation failure when copying "
2468                                        "username");
2469                         retval = PAM_SERVICE_ERR;
2470                         goto out;
2471                 }
2472         }
2473
2474         /* Maybe this was a UPN */
2475
2476         if (strchr(real_username, '@') != NULL) {
2477                 char *samaccountname = NULL;
2478
2479                 samaccountname = winbind_upn_to_username(ctx,
2480                                                          real_username);
2481                 if (samaccountname) {
2482                         free(real_username);
2483                         real_username = strdup(samaccountname);
2484                 }
2485         }
2486
2487         retval = _winbind_read_password(ctx, ctx->ctrl, NULL,
2488                                         "Password: ", NULL,
2489                                         &password);
2490
2491         if (retval != PAM_SUCCESS) {
2492                 _pam_log(ctx, LOG_ERR,
2493                          "Could not retrieve user's password");
2494                 retval = PAM_AUTHTOK_ERR;
2495                 goto out;
2496         }
2497
2498         /* Let's not give too much away in the log file */
2499
2500 #ifdef DEBUG_PASSWORD
2501         _pam_log_debug(ctx, LOG_INFO,
2502                        "Verify user '%s' with password '%s'",
2503                        real_username, password);
2504 #else
2505         _pam_log_debug(ctx, LOG_INFO,
2506                        "Verify user '%s'", real_username);
2507 #endif
2508
2509         member = get_member_from_config(ctx);
2510         cctype = get_krb5_cc_type_from_config(ctx);
2511         warn_pwd_expire = get_warn_pwd_expire_from_config(ctx);
2512
2513         /* Now use the username to look up password */
2514         retval = winbind_auth_request(ctx, real_username, password,
2515                                       member, cctype, warn_pwd_expire,
2516                                       NULL, NULL, NULL,
2517                                       NULL, &username_ret);
2518
2519         if (retval == PAM_NEW_AUTHTOK_REQD ||
2520             retval == PAM_AUTHTOK_EXPIRED) {
2521
2522                 char *new_authtok_required_during_auth = NULL;
2523
2524                 new_authtok_required = talloc_asprintf(NULL, "%d", retval);
2525                 if (!new_authtok_required) {
2526                         retval = PAM_BUF_ERR;
2527                         goto out;
2528                 }
2529
2530                 pam_set_data(pamh, PAM_WINBIND_NEW_AUTHTOK_REQD,
2531                              new_authtok_required,
2532                              _pam_winbind_cleanup_func);
2533
2534                 retval = PAM_SUCCESS;
2535
2536                 new_authtok_required_during_auth = talloc_asprintf(NULL, "%d", true);
2537                 if (!new_authtok_required_during_auth) {
2538                         retval = PAM_BUF_ERR;
2539                         goto out;
2540                 }
2541
2542                 pam_set_data(pamh, PAM_WINBIND_NEW_AUTHTOK_REQD_DURING_AUTH,
2543                              new_authtok_required_during_auth,
2544                              _pam_winbind_cleanup_func);
2545
2546                 goto out;
2547         }
2548
2549 out:
2550         if (username_ret) {
2551                 pam_set_item (pamh, PAM_USER, username_ret);
2552                 _pam_log_debug(ctx, LOG_INFO,
2553                                "Returned user was '%s'", username_ret);
2554                 free(username_ret);
2555         }
2556
2557         if (real_username) {
2558                 free(real_username);
2559         }
2560
2561         if (!new_authtok_required) {
2562                 pam_set_data(pamh, PAM_WINBIND_NEW_AUTHTOK_REQD, NULL, NULL);
2563         }
2564
2565         if (retval != PAM_SUCCESS) {
2566                 _pam_free_data_info3(pamh);
2567         }
2568
2569         _PAM_LOG_FUNCTION_LEAVE("pam_sm_authenticate", ctx, retval);
2570
2571         TALLOC_FREE(ctx);
2572
2573         return retval;
2574 }
2575
2576 PAM_EXTERN
2577 int pam_sm_setcred(pam_handle_t *pamh, int flags,
2578                    int argc, const char **argv)
2579 {
2580         int ret = PAM_SYSTEM_ERR;
2581         struct pwb_context *ctx = NULL;
2582
2583         ret = _pam_winbind_init_context(pamh, flags, argc, argv, &ctx);
2584         if (ret) {
2585                 goto out;
2586         }
2587
2588         _PAM_LOG_FUNCTION_ENTER("pam_sm_setcred", ctx);
2589
2590         switch (flags & ~PAM_SILENT) {
2591
2592                 case PAM_DELETE_CRED:
2593                         ret = _pam_delete_cred(pamh, flags, argc, argv);
2594                         break;
2595                 case PAM_REFRESH_CRED:
2596                         _pam_log_debug(ctx, LOG_WARNING,
2597                                        "PAM_REFRESH_CRED not implemented");
2598                         ret = PAM_SUCCESS;
2599                         break;
2600                 case PAM_REINITIALIZE_CRED:
2601                         _pam_log_debug(ctx, LOG_WARNING,
2602                                        "PAM_REINITIALIZE_CRED not implemented");
2603                         ret = PAM_SUCCESS;
2604                         break;
2605                 case PAM_ESTABLISH_CRED:
2606                         _pam_log_debug(ctx, LOG_WARNING,
2607                                        "PAM_ESTABLISH_CRED not implemented");
2608                         ret = PAM_SUCCESS;
2609                         break;
2610                 default:
2611                         ret = PAM_SYSTEM_ERR;
2612                         break;
2613         }
2614
2615  out:
2616
2617         _PAM_LOG_FUNCTION_LEAVE("pam_sm_setcred", ctx, ret);
2618
2619         TALLOC_FREE(ctx);
2620
2621         return ret;
2622 }
2623
2624 /*
2625  * Account management. We want to verify that the account exists
2626  * before returning PAM_SUCCESS
2627  */
2628 PAM_EXTERN
2629 int pam_sm_acct_mgmt(pam_handle_t *pamh, int flags,
2630                    int argc, const char **argv)
2631 {
2632         const char *username;
2633         int ret = PAM_USER_UNKNOWN;
2634         void *tmp = NULL;
2635         struct pwb_context *ctx = NULL;
2636
2637         ret = _pam_winbind_init_context(pamh, flags, argc, argv, &ctx);
2638         if (ret) {
2639                 goto out;
2640         }
2641
2642         _PAM_LOG_FUNCTION_ENTER("pam_sm_acct_mgmt", ctx);
2643
2644
2645         /* Get the username */
2646         ret = pam_get_user(pamh, &username, NULL);
2647         if ((ret != PAM_SUCCESS) || (!username)) {
2648                 _pam_log_debug(ctx, LOG_DEBUG,
2649                                "can not get the username");
2650                 ret = PAM_SERVICE_ERR;
2651                 goto out;
2652         }
2653
2654         /* Verify the username */
2655         ret = valid_user(ctx, username);
2656         switch (ret) {
2657         case -1:
2658                 /* some sort of system error. The log was already printed */
2659                 ret = PAM_SERVICE_ERR;
2660                 goto out;
2661         case 1:
2662                 /* the user does not exist */
2663                 _pam_log_debug(ctx, LOG_NOTICE, "user '%s' not found",
2664                                username);
2665                 if (ctx->ctrl & WINBIND_UNKNOWN_OK_ARG) {
2666                         ret = PAM_IGNORE;
2667                         goto out;
2668                 }
2669                 ret = PAM_USER_UNKNOWN;
2670                 goto out;
2671         case 0:
2672                 pam_get_data(pamh, PAM_WINBIND_NEW_AUTHTOK_REQD,
2673                              (const void **)&tmp);
2674                 if (tmp != NULL) {
2675                         ret = atoi((const char *)tmp);
2676                         switch (ret) {
2677                         case PAM_AUTHTOK_EXPIRED:
2678                                 /* fall through, since new token is required in this case */
2679                         case PAM_NEW_AUTHTOK_REQD:
2680                                 _pam_log(ctx, LOG_WARNING,
2681                                          "pam_sm_acct_mgmt success but %s is set",
2682                                          PAM_WINBIND_NEW_AUTHTOK_REQD);
2683                                 _pam_log(ctx, LOG_NOTICE,
2684                                          "user '%s' needs new password",
2685                                          username);
2686                                 /* PAM_AUTHTOKEN_REQD does not exist, but is documented in the manpage */
2687                                 ret = PAM_NEW_AUTHTOK_REQD;
2688                                 goto out;
2689                         default:
2690                                 _pam_log(ctx, LOG_WARNING,
2691                                          "pam_sm_acct_mgmt success");
2692                                 _pam_log(ctx, LOG_NOTICE,
2693                                          "user '%s' granted access", username);
2694                                 ret = PAM_SUCCESS;
2695                                 goto out;
2696                         }
2697                 }
2698
2699                 /* Otherwise, the authentication looked good */
2700                 _pam_log(ctx, LOG_NOTICE,
2701                          "user '%s' granted access", username);
2702                 ret = PAM_SUCCESS;
2703                 goto out;
2704         default:
2705                 /* we don't know anything about this return value */
2706                 _pam_log(ctx, LOG_ERR,
2707                          "internal module error (ret = %d, user = '%s')",
2708                          ret, username);
2709                 ret = PAM_SERVICE_ERR;
2710                 goto out;
2711         }
2712
2713         /* should not be reached */
2714         ret = PAM_IGNORE;
2715
2716  out:
2717
2718         _PAM_LOG_FUNCTION_LEAVE("pam_sm_acct_mgmt", ctx, ret);
2719
2720         TALLOC_FREE(ctx);
2721
2722         return ret;
2723 }
2724
2725 PAM_EXTERN
2726 int pam_sm_open_session(pam_handle_t *pamh, int flags,
2727                         int argc, const char **argv)
2728 {
2729         int ret = PAM_SUCCESS;
2730         struct pwb_context *ctx = NULL;
2731
2732         ret = _pam_winbind_init_context(pamh, flags, argc, argv, &ctx);
2733         if (ret) {
2734                 goto out;
2735         }
2736
2737         _PAM_LOG_FUNCTION_ENTER("pam_sm_open_session", ctx);
2738
2739         if (ctx->ctrl & WINBIND_MKHOMEDIR) {
2740                 /* check and create homedir */
2741                 ret = _pam_mkhomedir(ctx);
2742         }
2743  out:
2744         _PAM_LOG_FUNCTION_LEAVE("pam_sm_open_session", ctx, ret);
2745
2746         TALLOC_FREE(ctx);
2747
2748         return ret;
2749 }
2750
2751 PAM_EXTERN
2752 int pam_sm_close_session(pam_handle_t *pamh, int flags,
2753                          int argc, const char **argv)
2754 {
2755         int ret = PAM_SUCCESS;
2756         struct pwb_context *ctx = NULL;
2757
2758         ret = _pam_winbind_init_context(pamh, flags, argc, argv, &ctx);
2759         if (ret) {
2760                 goto out;
2761         }
2762
2763         _PAM_LOG_FUNCTION_ENTER("pam_sm_close_session", ctx);
2764
2765 out:
2766         _PAM_LOG_FUNCTION_LEAVE("pam_sm_close_session", ctx, ret);
2767
2768         TALLOC_FREE(ctx);
2769
2770         return ret;
2771 }
2772
2773 /**
2774  * evaluate whether we need to re-authenticate with kerberos after a
2775  * password change
2776  *
2777  * @param ctx PAM winbind context.
2778  * @param user The username
2779  *
2780  * @return boolean Returns true if required, false if not.
2781  */
2782
2783 static bool _pam_require_krb5_auth_after_chauthtok(struct pwb_context *ctx,
2784                                                    const char *user)
2785 {
2786
2787         /* Make sure that we only do this if a) the chauthtok got initiated
2788          * during a logon attempt (authenticate->acct_mgmt->chauthtok) b) any
2789          * later password change via the "passwd" command if done by the user
2790          * itself
2791          * NB. If we login from gdm or xdm and the password expires,
2792          * we change the password, but there is no memory cache.
2793          * Thus, even for passthrough login, we should do the
2794          * authentication again to update memory cache.
2795          * --- BoYang
2796          * */
2797
2798         char *new_authtok_reqd_during_auth = NULL;
2799         struct passwd *pwd = NULL;
2800
2801         _pam_get_data(ctx->pamh, PAM_WINBIND_NEW_AUTHTOK_REQD_DURING_AUTH,
2802                       &new_authtok_reqd_during_auth);
2803         pam_set_data(ctx->pamh, PAM_WINBIND_NEW_AUTHTOK_REQD_DURING_AUTH,
2804                      NULL, NULL);
2805
2806         if (new_authtok_reqd_during_auth) {
2807                 return true;
2808         }
2809
2810         pwd = getpwnam(user);
2811         if (!pwd) {
2812                 return false;
2813         }
2814
2815         if (getuid() == pwd->pw_uid) {
2816                 return true;
2817         }
2818
2819         return false;
2820 }
2821
2822
2823 PAM_EXTERN
2824 int pam_sm_chauthtok(pam_handle_t * pamh, int flags,
2825                      int argc, const char **argv)
2826 {
2827         unsigned int lctrl;
2828         int ret;
2829         bool cached_login = false;
2830
2831         /* <DO NOT free() THESE> */
2832         const char *user;
2833         char *pass_old, *pass_new;
2834         /* </DO NOT free() THESE> */
2835
2836         char *Announce;
2837
2838         int retry = 0;
2839         char *username_ret = NULL;
2840         struct wbcAuthErrorInfo *error = NULL;
2841         struct pwb_context *ctx = NULL;
2842
2843         ret = _pam_winbind_init_context(pamh, flags, argc, argv, &ctx);
2844         if (ret) {
2845                 goto out;
2846         }
2847
2848         _PAM_LOG_FUNCTION_ENTER("pam_sm_chauthtok", ctx);
2849
2850         cached_login = (ctx->ctrl & WINBIND_CACHED_LOGIN);
2851
2852         /* clearing offline bit for auth */
2853         ctx->ctrl &= ~WINBIND_CACHED_LOGIN;
2854
2855         /*
2856          * First get the name of a user
2857          */
2858         ret = pam_get_user(pamh, &user, "Username: ");
2859         if (ret) {
2860                 _pam_log(ctx, LOG_ERR,
2861                          "password - could not identify user");
2862                 goto out;
2863         }
2864
2865         if (user == NULL) {
2866                 _pam_log(ctx, LOG_ERR, "username was NULL!");
2867                 ret = PAM_USER_UNKNOWN;
2868                 goto out;
2869         }
2870
2871         _pam_log_debug(ctx, LOG_DEBUG, "username [%s] obtained", user);
2872
2873         /* check if this is really a user in winbindd, not only in NSS */
2874         ret = valid_user(ctx, user);
2875         switch (ret) {
2876                 case 1:
2877                         ret = PAM_USER_UNKNOWN;
2878                         goto out;
2879                 case -1:
2880                         ret = PAM_SYSTEM_ERR;
2881                         goto out;
2882                 default:
2883                         break;
2884         }
2885
2886         /*
2887          * obtain and verify the current password (OLDAUTHTOK) for
2888          * the user.
2889          */
2890
2891         if (flags & PAM_PRELIM_CHECK) {
2892                 time_t pwdlastset_prelim = 0;
2893
2894                 /* instruct user what is happening */
2895
2896 #define greeting "Changing password for"
2897                 Announce = talloc_asprintf(ctx, "%s %s", greeting, user);
2898                 if (!Announce) {
2899                         _pam_log(ctx, LOG_CRIT,
2900                                  "password - out of memory");
2901                         ret = PAM_BUF_ERR;
2902                         goto out;
2903                 }
2904 #undef greeting
2905
2906                 lctrl = ctx->ctrl | WINBIND__OLD_PASSWORD;
2907                 ret = _winbind_read_password(ctx, lctrl,
2908                                                 Announce,
2909                                                 "(current) NT password: ",
2910                                                 NULL,
2911                                                 (const char **) &pass_old);
2912                 TALLOC_FREE(Announce);
2913                 if (ret != PAM_SUCCESS) {
2914                         _pam_log(ctx, LOG_NOTICE,
2915                                  "password - (old) token not obtained");
2916                         goto out;
2917                 }
2918
2919                 /* verify that this is the password for this user */
2920
2921                 ret = winbind_auth_request(ctx, user, pass_old,
2922                                            NULL, NULL, 0,
2923                                            &error, NULL, NULL,
2924                                            &pwdlastset_prelim, NULL);
2925
2926                 if (ret != PAM_ACCT_EXPIRED &&
2927                     ret != PAM_AUTHTOK_EXPIRED &&
2928                     ret != PAM_NEW_AUTHTOK_REQD &&
2929                     ret != PAM_SUCCESS) {
2930                         pass_old = NULL;
2931                         goto out;
2932                 }
2933
2934                 pam_set_data(pamh, PAM_WINBIND_PWD_LAST_SET,
2935                              (void *)pwdlastset_prelim, NULL);
2936
2937                 ret = pam_set_item(pamh, PAM_OLDAUTHTOK,
2938                                    (const void *) pass_old);
2939                 pass_old = NULL;
2940                 if (ret != PAM_SUCCESS) {
2941                         _pam_log(ctx, LOG_CRIT,
2942                                  "failed to set PAM_OLDAUTHTOK");
2943                 }
2944         } else if (flags & PAM_UPDATE_AUTHTOK) {
2945
2946                 time_t pwdlastset_update = 0;
2947
2948                 /*
2949                  * obtain the proposed password
2950                  */
2951
2952                 /*
2953                  * get the old token back.
2954                  */
2955
2956                 ret = _pam_get_item(pamh, PAM_OLDAUTHTOK, &pass_old);
2957
2958                 if (ret != PAM_SUCCESS) {
2959                         _pam_log(ctx, LOG_NOTICE,
2960                                  "user not authenticated");
2961                         goto out;
2962                 }
2963
2964                 lctrl = ctx->ctrl & ~WINBIND_TRY_FIRST_PASS_ARG;
2965
2966                 if (on(WINBIND_USE_AUTHTOK_ARG, lctrl)) {
2967                         lctrl |= WINBIND_USE_FIRST_PASS_ARG;
2968                 }
2969                 retry = 0;
2970                 ret = PAM_AUTHTOK_ERR;
2971                 while ((ret != PAM_SUCCESS) && (retry++ < MAX_PASSWD_TRIES)) {
2972                         /*
2973                          * use_authtok is to force the use of a previously entered
2974                          * password -- needed for pluggable password strength checking
2975                          */
2976
2977                         ret = _winbind_read_password(ctx, lctrl,
2978                                                      NULL,
2979                                                      "Enter new NT password: ",
2980                                                      "Retype new NT password: ",
2981                                                      (const char **)&pass_new);
2982
2983                         if (ret != PAM_SUCCESS) {
2984                                 _pam_log_debug(ctx, LOG_ALERT,
2985                                                "password - "
2986                                                "new password not obtained");
2987                                 pass_old = NULL;/* tidy up */
2988                                 goto out;
2989                         }
2990
2991                         /*
2992                          * At this point we know who the user is and what they
2993                          * propose as their new password. Verify that the new
2994                          * password is acceptable.
2995                          */
2996
2997                         if (pass_new[0] == '\0') {/* "\0" password = NULL */
2998                                 pass_new = NULL;
2999                         }
3000                 }
3001
3002                 /*
3003                  * By reaching here we have approved the passwords and must now
3004                  * rebuild the password database file.
3005                  */
3006                 _pam_get_data(pamh, PAM_WINBIND_PWD_LAST_SET,
3007                               &pwdlastset_update);
3008
3009                 /*
3010                  * if cached creds were enabled, make sure to set the
3011                  * WINBIND_CACHED_LOGIN bit here in order to have winbindd
3012                  * update the cached creds storage - gd
3013                  */
3014                 if (cached_login) {
3015                         ctx->ctrl |= WINBIND_CACHED_LOGIN;
3016                 }
3017
3018                 ret = winbind_chauthtok_request(ctx, user, pass_old,
3019                                                 pass_new, pwdlastset_update);
3020                 if (ret) {
3021                         _pam_overwrite(pass_new);
3022                         _pam_overwrite(pass_old);
3023                         pass_old = pass_new = NULL;
3024                         goto out;
3025                 }
3026
3027                 if (_pam_require_krb5_auth_after_chauthtok(ctx, user)) {
3028
3029                         const char *member = NULL;
3030                         const char *cctype = NULL;
3031                         int warn_pwd_expire;
3032                         struct wbcLogonUserInfo *info = NULL;
3033                         struct wbcUserPasswordPolicyInfo *policy = NULL;
3034
3035                         member = get_member_from_config(ctx);
3036                         cctype = get_krb5_cc_type_from_config(ctx);
3037                         warn_pwd_expire = get_warn_pwd_expire_from_config(ctx);
3038
3039                         /* Keep WINBIND_CACHED_LOGIN bit for
3040                          * authentication after changing the password.
3041                          * This will update the cached credentials in case
3042                          * that winbindd_dual_pam_chauthtok() fails
3043                          * to update them.
3044                          * --- BoYang
3045                          * */
3046
3047                         ret = winbind_auth_request(ctx, user, pass_new,
3048                                                    member, cctype, 0,
3049                                                    &error, &info, &policy,
3050                                                    NULL, &username_ret);
3051                         _pam_overwrite(pass_new);
3052                         _pam_overwrite(pass_old);
3053                         pass_old = pass_new = NULL;
3054
3055                         if (ret == PAM_SUCCESS) {
3056
3057                                 struct wbcAuthUserInfo *user_info = NULL;
3058
3059                                 if (info && info->info) {
3060                                         user_info = info->info;
3061                                 }
3062
3063                                 /* warn a user if the password is about to
3064                                  * expire soon */
3065                                 _pam_warn_password_expiry(ctx, user_info, policy,
3066                                                           warn_pwd_expire,
3067                                                           NULL);
3068
3069                                 /* set some info3 info for other modules in the
3070                                  * stack */
3071                                 _pam_set_data_info3(ctx, user_info);
3072
3073                                 /* put krb5ccname into env */
3074                                 _pam_setup_krb5_env(ctx, info);
3075
3076                                 if (username_ret) {
3077                                         pam_set_item(pamh, PAM_USER,
3078                                                      username_ret);
3079                                         _pam_log_debug(ctx, LOG_INFO,
3080                                                        "Returned user was '%s'",
3081                                                        username_ret);
3082                                         free(username_ret);
3083                                 }
3084
3085                                 wbcFreeMemory(info);
3086                                 wbcFreeMemory(policy);
3087                         }
3088
3089                         goto out;
3090                 }
3091         } else {
3092                 ret = PAM_SERVICE_ERR;
3093         }
3094
3095 out:
3096         {
3097                 /* Deal with offline errors. */
3098                 int i;
3099                 const char *codes[] = {
3100                         "NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND",
3101                         "NT_STATUS_NO_LOGON_SERVERS",
3102                         "NT_STATUS_ACCESS_DENIED"
3103                 };
3104
3105                 for (i=0; i<ARRAY_SIZE(codes); i++) {
3106                         int _ret;
3107                         if (_pam_check_remark_auth_err(ctx, error, codes[i], &_ret)) {
3108                                 break;
3109                         }
3110                 }
3111         }
3112
3113         wbcFreeMemory(error);
3114
3115         _PAM_LOG_FUNCTION_LEAVE("pam_sm_chauthtok", ctx, ret);
3116
3117         TALLOC_FREE(ctx);
3118
3119         return ret;
3120 }
3121
3122 #ifdef PAM_STATIC
3123
3124 /* static module data */
3125
3126 struct pam_module _pam_winbind_modstruct = {
3127         MODULE_NAME,
3128         pam_sm_authenticate,
3129         pam_sm_setcred,
3130         pam_sm_acct_mgmt,
3131         pam_sm_open_session,
3132         pam_sm_close_session,
3133         pam_sm_chauthtok
3134 };
3135
3136 #endif
3137
3138 /*
3139  * Copyright (c) Andrew Tridgell  <tridge@samba.org>   2000
3140  * Copyright (c) Tim Potter       <tpot@samba.org>     2000
3141  * Copyright (c) Andrew Bartlettt <abartlet@samba.org> 2002
3142  * Copyright (c) Guenther Deschner <gd@samba.org>      2005-2008
3143  * Copyright (c) Jan Rêkorajski 1999.
3144  * Copyright (c) Andrew G. Morgan 1996-8.
3145  * Copyright (c) Alex O. Yuriev, 1996.
3146  * Copyright (c) Cristian Gafton 1996.
3147  * Copyright (C) Elliot Lee <sopwith@redhat.com> 1996, Red Hat Software.
3148  *
3149  * Redistribution and use in source and binary forms, with or without
3150  * modification, are permitted provided that the following conditions
3151  * are met:
3152  * 1. Redistributions of source code must retain the above copyright
3153  *    notice, and the entire permission notice in its entirety,
3154  *    including the disclaimer of warranties.
3155  * 2. Redistributions in binary form must reproduce the above copyright
3156  *    notice, this list of conditions and the following disclaimer in the
3157  *    documentation and/or other materials provided with the distribution.
3158  * 3. The name of the author may not be used to endorse or promote
3159  *    products derived from this software without specific prior
3160  *    written permission.
3161  *
3162  * ALTERNATIVELY, this product may be distributed under the terms of
3163  * the GNU Public License, in which case the provisions of the GPL are
3164  * required INSTEAD OF the above restrictions.  (This clause is
3165  * necessary due to a potential bad interaction between the GPL and
3166  * the restrictions contained in a BSD-style copyright.)
3167  *
3168  * THIS SOFTWARE IS PROVIDED `AS IS'' AND ANY EXPRESS OR IMPLIED
3169  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
3170  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
3171  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
3172  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
3173  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
3174  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3175  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
3176  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
3177  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
3178  * OF THE POSSIBILITY OF SUCH DAMAGE.
3179  */