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