Fix bug #9098 - winbind does not refresh kerberos tickets.
[samba.git] / source3 / winbindd / winbindd_cred_cache.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    Winbind daemon - krb5 credential cache functions
5    and in-memory cache functions.
6
7    Copyright (C) Guenther Deschner 2005-2006
8    Copyright (C) Jeremy Allison 2006
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "includes.h"
25 #include "winbindd.h"
26 #include "../libcli/auth/libcli_auth.h"
27 #include "smb_krb5.h"
28
29 #undef DBGC_CLASS
30 #define DBGC_CLASS DBGC_WINBIND
31
32 /* uncomment this to do fast debugging on the krb5 ticket renewal event */
33 #ifdef DEBUG_KRB5_TKT_RENEWAL
34 #undef DEBUG_KRB5_TKT_RENEWAL
35 #endif
36
37 #define MAX_CCACHES 100
38
39 static struct WINBINDD_CCACHE_ENTRY *ccache_list;
40 static void krb5_ticket_gain_handler(struct event_context *,
41                                      struct timed_event *,
42                                      struct timeval,
43                                      void *);
44 static void add_krb5_ticket_gain_handler_event(struct WINBINDD_CCACHE_ENTRY *,
45                                      struct timeval);
46
47 /* The Krb5 ticket refresh handler should be scheduled
48    at one-half of the period from now till the tkt
49    expiration */
50 #define KRB5_EVENT_REFRESH_TIME(x) ((x) - (((x) - time(NULL))/2))
51
52 /****************************************************************
53  Find an entry by name.
54 ****************************************************************/
55
56 static struct WINBINDD_CCACHE_ENTRY *get_ccache_by_username(const char *username)
57 {
58         struct WINBINDD_CCACHE_ENTRY *entry;
59
60         for (entry = ccache_list; entry; entry = entry->next) {
61                 if (strequal(entry->username, username)) {
62                         return entry;
63                 }
64         }
65         return NULL;
66 }
67
68 /****************************************************************
69  How many do we have ?
70 ****************************************************************/
71
72 static int ccache_entry_count(void)
73 {
74         struct WINBINDD_CCACHE_ENTRY *entry;
75         int i = 0;
76
77         for (entry = ccache_list; entry; entry = entry->next) {
78                 i++;
79         }
80         return i;
81 }
82
83 void ccache_remove_all_after_fork(void)
84 {
85         struct WINBINDD_CCACHE_ENTRY *cur, *next;
86
87         for (cur = ccache_list; cur; cur = next) {
88                 next = cur->next;
89                 DLIST_REMOVE(ccache_list, cur);
90                 TALLOC_FREE(cur->event);
91                 TALLOC_FREE(cur);
92         }
93
94         return;
95 }
96
97 /****************************************************************
98  Do the work of refreshing the ticket.
99 ****************************************************************/
100
101 static void krb5_ticket_refresh_handler(struct event_context *event_ctx,
102                                         struct timed_event *te,
103                                         struct timeval now,
104                                         void *private_data)
105 {
106         struct WINBINDD_CCACHE_ENTRY *entry =
107                 talloc_get_type_abort(private_data, struct WINBINDD_CCACHE_ENTRY);
108 #ifdef HAVE_KRB5
109         int ret;
110         time_t new_start;
111         time_t expire_time = 0;
112         struct WINBINDD_MEMORY_CREDS *cred_ptr = entry->cred_ptr;
113 #endif
114
115         DEBUG(10,("krb5_ticket_refresh_handler called\n"));
116         DEBUGADD(10,("event called for: %s, %s\n",
117                 entry->ccname, entry->username));
118
119         TALLOC_FREE(entry->event);
120
121 #ifdef HAVE_KRB5
122
123         /* Kinit again if we have the user password and we can't renew the old
124          * tgt anymore 
125          * NB
126          * This happens when machine are put to sleep for a very long time. */
127
128         if (entry->renew_until < time(NULL)) {
129 rekinit:
130                 if (cred_ptr && cred_ptr->pass) {
131
132                         set_effective_uid(entry->uid);
133
134                         ret = kerberos_kinit_password_ext(entry->principal_name,
135                                                           cred_ptr->pass,
136                                                           0, /* hm, can we do time correction here ? */
137                                                           &entry->refresh_time,
138                                                           &entry->renew_until,
139                                                           entry->ccname,
140                                                           False, /* no PAC required anymore */
141                                                           True,
142                                                           WINBINDD_PAM_AUTH_KRB5_RENEW_TIME,
143                                                           NULL);
144                         gain_root_privilege();
145
146                         if (ret) {
147                                 DEBUG(3,("krb5_ticket_refresh_handler: "
148                                         "could not re-kinit: %s\n",
149                                         error_message(ret)));
150                                 /* destroy the ticket because we cannot rekinit
151                                  * it, ignore error here */
152                                 ads_kdestroy(entry->ccname);
153
154                                 /* Don't break the ticket refresh chain: retry 
155                                  * refreshing ticket sometime later when KDC is 
156                                  * unreachable -- BoYang. More error code handling
157                                  * here? 
158                                  * */
159
160                                 if ((ret == KRB5_KDC_UNREACH)
161                                     || (ret == KRB5_REALM_CANT_RESOLVE)) {
162 #if defined(DEBUG_KRB5_TKT_RENEWAL)
163                                         new_start = time(NULL) + 30;
164 #else
165                                         new_start = time(NULL) +
166                                                     MAX(30, lp_winbind_cache_time());
167 #endif
168                                         add_krb5_ticket_gain_handler_event(entry,
169                                                         timeval_set(new_start, 0));
170                                         return;
171                                 }
172                                 TALLOC_FREE(entry->event);
173                                 return;
174                         }
175
176                         DEBUG(10,("krb5_ticket_refresh_handler: successful re-kinit "
177                                 "for: %s in ccache: %s\n",
178                                 entry->principal_name, entry->ccname));
179
180 #if defined(DEBUG_KRB5_TKT_RENEWAL)
181                         new_start = time(NULL) + 30;
182 #else
183                         /* The tkt should be refreshed at one-half the period
184                            from now to the expiration time */
185                         expire_time = entry->refresh_time;
186                         new_start = KRB5_EVENT_REFRESH_TIME(entry->refresh_time);
187 #endif
188                         goto done;
189                 } else {
190                                 /* can this happen? 
191                                  * No cached credentials
192                                  * destroy ticket and refresh chain 
193                                  * */
194                                 ads_kdestroy(entry->ccname);
195                                 TALLOC_FREE(entry->event);
196                                 return;
197                 }
198         }
199
200         set_effective_uid(entry->uid);
201
202         ret = smb_krb5_renew_ticket(entry->ccname,
203                                     entry->principal_name,
204                                     entry->service,
205                                     &new_start);
206 #if defined(DEBUG_KRB5_TKT_RENEWAL)
207         new_start = time(NULL) + 30;
208 #else
209         expire_time = new_start;
210         new_start = KRB5_EVENT_REFRESH_TIME(new_start);
211 #endif
212
213         gain_root_privilege();
214
215         if (ret) {
216                 DEBUG(3,("krb5_ticket_refresh_handler: "
217                         "could not renew tickets: %s\n",
218                         error_message(ret)));
219                 /* maybe we are beyond the renewing window */
220
221                 /* evil rises here, we refresh ticket failed,
222                  * but the ticket might be expired. Therefore,
223                  * When we refresh ticket failed, destory the 
224                  * ticket */
225
226                 ads_kdestroy(entry->ccname);
227
228                 /* avoid breaking the renewal chain: retry in
229                  * lp_winbind_cache_time() seconds when the KDC was not
230                  * available right now. 
231                  * the return code can be KRB5_REALM_CANT_RESOLVE. 
232                  * More error code handling here? */
233
234                 if ((ret == KRB5_KDC_UNREACH) 
235                     || (ret == KRB5_REALM_CANT_RESOLVE)) {
236 #if defined(DEBUG_KRB5_TKT_RENEWAL)
237                         new_start = time(NULL) + 30;
238 #else
239                         new_start = time(NULL) +
240                                     MAX(30, lp_winbind_cache_time());
241 #endif
242                         /* ticket is destroyed here, we have to regain it
243                          * if it is possible */
244                         add_krb5_ticket_gain_handler_event(entry,
245                                                 timeval_set(new_start, 0));
246                         return;
247                 }
248
249                 /* This is evil, if the ticket was already expired.
250                  * renew ticket function returns KRB5KRB_AP_ERR_TKT_EXPIRED.
251                  * But there is still a chance that we can rekinit it. 
252                  *
253                  * This happens when user login in online mode, and then network
254                  * down or something cause winbind goes offline for a very long time,
255                  * and then goes online again. ticket expired, renew failed.
256                  * This happens when machine are put to sleep for a long time,
257                  * but shorter than entry->renew_util.
258                  * NB
259                  * Looks like the KDC is reachable, we want to rekinit as soon as
260                  * possible instead of waiting some time later. */
261                 if ((ret == KRB5KRB_AP_ERR_TKT_EXPIRED)
262                     || (ret == KRB5_FCC_NOFILE)) goto rekinit;
263
264                 return;
265         }
266
267 done:
268         /* in cases that ticket will be unrenewable soon, we don't try to renew ticket 
269          * but try to regain ticket if it is possible */
270         if (entry->renew_until && expire_time
271              && (entry->renew_until <= expire_time)) {
272                 /* try to regain ticket 10 seconds beforre expiration */
273                 expire_time -= 10;
274                 add_krb5_ticket_gain_handler_event(entry,
275                                         timeval_set(expire_time, 0));
276                 return;
277         }
278
279         if (entry->refresh_time == 0) {
280                 entry->refresh_time = new_start;
281         }
282         entry->event = event_add_timed(winbind_event_context(), entry,
283                                        timeval_set(new_start, 0),
284                                        krb5_ticket_refresh_handler,
285                                        entry);
286
287 #endif
288 }
289
290 /****************************************************************
291  Do the work of regaining a ticket when coming from offline auth.
292 ****************************************************************/
293
294 static void krb5_ticket_gain_handler(struct event_context *event_ctx,
295                                      struct timed_event *te,
296                                      struct timeval now,
297                                      void *private_data)
298 {
299         struct WINBINDD_CCACHE_ENTRY *entry =
300                 talloc_get_type_abort(private_data, struct WINBINDD_CCACHE_ENTRY);
301 #ifdef HAVE_KRB5
302         int ret;
303         struct timeval t;
304         struct WINBINDD_MEMORY_CREDS *cred_ptr = entry->cred_ptr;
305         struct winbindd_domain *domain = NULL;
306 #endif
307
308         DEBUG(10,("krb5_ticket_gain_handler called\n"));
309         DEBUGADD(10,("event called for: %s, %s\n",
310                 entry->ccname, entry->username));
311
312         TALLOC_FREE(entry->event);
313
314 #ifdef HAVE_KRB5
315
316         if (!cred_ptr || !cred_ptr->pass) {
317                 DEBUG(10,("krb5_ticket_gain_handler: no memory creds\n"));
318                 return;
319         }
320
321         if ((domain = find_domain_from_name(entry->realm)) == NULL) {
322                 DEBUG(0,("krb5_ticket_gain_handler: unknown domain\n"));
323                 return;
324         }
325
326         if (!domain->online) {
327                 goto retry_later;
328         }
329
330         set_effective_uid(entry->uid);
331
332         ret = kerberos_kinit_password_ext(entry->principal_name,
333                                           cred_ptr->pass,
334                                           0, /* hm, can we do time correction here ? */
335                                           &entry->refresh_time,
336                                           &entry->renew_until,
337                                           entry->ccname,
338                                           False, /* no PAC required anymore */
339                                           True,
340                                           WINBINDD_PAM_AUTH_KRB5_RENEW_TIME,
341                                           NULL);
342         gain_root_privilege();
343
344         if (ret) {
345                 DEBUG(3,("krb5_ticket_gain_handler: "
346                         "could not kinit: %s\n",
347                         error_message(ret)));
348                 /* evil. If we cannot do it, destroy any the __maybe__ 
349                  * __existing__ ticket */
350                 ads_kdestroy(entry->ccname);
351                 goto retry_later;
352         }
353
354         DEBUG(10,("krb5_ticket_gain_handler: "
355                 "successful kinit for: %s in ccache: %s\n",
356                 entry->principal_name, entry->ccname));
357
358         goto got_ticket;
359
360   retry_later:
361  
362 #if defined(DEBUG_KRB5_TKT_REGAIN)
363         t = timeval_set(time(NULL) + 30, 0);
364 #else
365         t = timeval_current_ofs(MAX(30, lp_winbind_cache_time()), 0);
366 #endif
367
368         add_krb5_ticket_gain_handler_event(entry, t);
369         return;
370
371   got_ticket:
372
373 #if defined(DEBUG_KRB5_TKT_RENEWAL)
374         t = timeval_set(time(NULL) + 30, 0);
375 #else
376         t = timeval_set(KRB5_EVENT_REFRESH_TIME(entry->refresh_time), 0);
377 #endif
378
379         if (entry->refresh_time == 0) {
380                 entry->refresh_time = t.tv_sec;
381         }
382         entry->event = event_add_timed(winbind_event_context(),
383                                        entry,
384                                        t,
385                                        krb5_ticket_refresh_handler,
386                                        entry);
387
388         return;
389 #endif
390 }
391
392 /**************************************************************
393  The gain initial ticket case is recognised as entry->refresh_time
394  is always zero.
395 **************************************************************/
396
397 static void add_krb5_ticket_gain_handler_event(struct WINBINDD_CCACHE_ENTRY *entry,
398                                      struct timeval t)
399 {
400         entry->refresh_time = 0;
401         entry->event = event_add_timed(winbind_event_context(),
402                                        entry,
403                                        t,
404                                        krb5_ticket_gain_handler,
405                                        entry);
406 }
407
408 void ccache_regain_all_now(void)
409 {
410         struct WINBINDD_CCACHE_ENTRY *cur;
411         struct timeval t = timeval_current();
412
413         for (cur = ccache_list; cur; cur = cur->next) {
414                 struct timed_event *new_event;
415
416                 /*
417                  * if refresh_time is 0, we know that the
418                  * the event has the krb5_ticket_gain_handler
419                  */
420                 if (cur->refresh_time == 0) {
421                         new_event = event_add_timed(winbind_event_context(),
422                                                     cur,
423                                                     t,
424                                                     krb5_ticket_gain_handler,
425                                                     cur);
426                 } else {
427                         new_event = event_add_timed(winbind_event_context(),
428                                                     cur,
429                                                     t,
430                                                     krb5_ticket_refresh_handler,
431                                                     cur);
432                 }
433
434                 if (!new_event) {
435                         continue;
436                 }
437
438                 TALLOC_FREE(cur->event);
439                 cur->event = new_event;
440         }
441
442         return;
443 }
444
445 /****************************************************************
446  Check if an ccache entry exists.
447 ****************************************************************/
448
449 bool ccache_entry_exists(const char *username)
450 {
451         struct WINBINDD_CCACHE_ENTRY *entry = get_ccache_by_username(username);
452         return (entry != NULL);
453 }
454
455 /****************************************************************
456  Ensure we're changing the correct entry.
457 ****************************************************************/
458
459 bool ccache_entry_identical(const char *username,
460                             uid_t uid,
461                             const char *ccname)
462 {
463         struct WINBINDD_CCACHE_ENTRY *entry = get_ccache_by_username(username);
464
465         if (!entry) {
466                 return False;
467         }
468
469         if (entry->uid != uid) {
470                 DEBUG(0,("cache_entry_identical: uid's differ: %u != %u\n",
471                         (unsigned int)entry->uid, (unsigned int)uid));
472                 return False;
473         }
474         if (!strcsequal(entry->ccname, ccname)) {
475                 DEBUG(0,("cache_entry_identical: "
476                         "ccnames differ: (cache) %s != (client) %s\n",
477                         entry->ccname, ccname));
478                 return False;
479         }
480         return True;
481 }
482
483 NTSTATUS add_ccache_to_list(const char *princ_name,
484                             const char *ccname,
485                             const char *service,
486                             const char *username,
487                             const char *pass,
488                             const char *realm,
489                             uid_t uid,
490                             time_t create_time,
491                             time_t ticket_end,
492                             time_t renew_until,
493                             bool postponed_request)
494 {
495         struct WINBINDD_CCACHE_ENTRY *entry = NULL;
496         struct timeval t;
497         NTSTATUS ntret;
498 #ifdef HAVE_KRB5
499         int ret;
500 #endif
501
502         if ((username == NULL && princ_name == NULL) ||
503             ccname == NULL || uid < 0) {
504                 return NT_STATUS_INVALID_PARAMETER;
505         }
506
507         if (ccache_entry_count() + 1 > MAX_CCACHES) {
508                 DEBUG(10,("add_ccache_to_list: "
509                         "max number of ccaches reached\n"));
510                 return NT_STATUS_NO_MORE_ENTRIES;
511         }
512
513         /* If it is cached login, destroy krb5 ticket
514          * to avoid surprise. */
515 #ifdef HAVE_KRB5
516         if (postponed_request) {
517                 /* ignore KRB5_FCC_NOFILE error here */
518                 ret = ads_kdestroy(ccname);
519                 if (ret == KRB5_FCC_NOFILE) {
520                         ret = 0;
521                 }
522                 if (ret) {
523                         DEBUG(0, ("add_ccache_to_list: failed to destroy "
524                                    "user krb5 ccache %s with %s\n", ccname,
525                                    error_message(ret)));
526                         return krb5_to_nt_status(ret);
527                 } else {
528                         DEBUG(10, ("add_ccache_to_list: successfully destroyed "
529                                    "krb5 ccache %s for user %s\n", ccname,
530                                    username));
531                 }
532         }
533 #endif
534
535         /* Reference count old entries */
536         entry = get_ccache_by_username(username);
537         if (entry) {
538                 /* Check cached entries are identical. */
539                 if (!ccache_entry_identical(username, uid, ccname)) {
540                         return NT_STATUS_INVALID_PARAMETER;
541                 }
542                 entry->ref_count++;
543                 DEBUG(10,("add_ccache_to_list: "
544                         "ref count on entry %s is now %d\n",
545                         username, entry->ref_count));
546                 /* FIXME: in this case we still might want to have a krb5 cred
547                  * event handler created - gd
548                  * Add ticket refresh handler here */
549                 
550                 if (!lp_winbind_refresh_tickets() || renew_until <= 0) {
551                         return NT_STATUS_OK;
552                 }
553                 
554                 if (!entry->event) {
555                         if (postponed_request) {
556                                 t = timeval_current_ofs(MAX(30, lp_winbind_cache_time()), 0);
557                                 add_krb5_ticket_gain_handler_event(entry, t);
558                         } else {
559                                 /* Renew at 1/2 the ticket expiration time */
560 #if defined(DEBUG_KRB5_TKT_RENEWAL)
561                                 t = timeval_set(time(NULL)+30, 0);
562 #else
563                                 t = timeval_set(KRB5_EVENT_REFRESH_TIME(ticket_end), 0);
564 #endif
565                                 if (!entry->refresh_time) {
566                                         entry->refresh_time = t.tv_sec;
567                                 }
568                                 entry->event = event_add_timed(winbind_event_context(),
569                                                                entry,
570                                                                t,
571                                                                krb5_ticket_refresh_handler,
572                                                                entry);
573                         }
574
575                         if (!entry->event) {
576                                 ntret = remove_ccache(username);
577                                 if (!NT_STATUS_IS_OK(ntret)) {
578                                         DEBUG(0, ("add_ccache_to_list: Failed to remove krb5 "
579                                                   "ccache %s for user %s\n", entry->ccname,
580                                                   entry->username));
581                                         DEBUG(0, ("add_ccache_to_list: error is %s\n",
582                                                   nt_errstr(ntret)));
583                                         return ntret;
584                                 }
585                                 return NT_STATUS_NO_MEMORY;
586                         }
587
588                         DEBUG(10,("add_ccache_to_list: added krb5_ticket handler\n"));
589                 }
590
591                 /*
592                  * If we're set up to renew our krb5 tickets, we must
593                  * cache the credentials in memory for the ticket
594                  * renew function (or increase the reference count
595                  * if we're logging in more than once). Fix inspired
596                  * by patch from Ian Gordon <ian.gordon@strath.ac.uk>
597                  * for bugid #9098.
598                  */
599
600                 ntret = winbindd_add_memory_creds(username, uid, pass);
601                 DEBUG(10, ("winbindd_add_memory_creds returned: %s\n",
602                         nt_errstr(ntret)));
603
604                 return NT_STATUS_OK;
605         }
606
607         entry = TALLOC_P(NULL, struct WINBINDD_CCACHE_ENTRY);
608         if (!entry) {
609                 return NT_STATUS_NO_MEMORY;
610         }
611
612         ZERO_STRUCTP(entry);
613
614         if (username) {
615                 entry->username = talloc_strdup(entry, username);
616                 if (!entry->username) {
617                         goto no_mem;
618                 }
619         }
620         if (princ_name) {
621                 entry->principal_name = talloc_strdup(entry, princ_name);
622                 if (!entry->principal_name) {
623                         goto no_mem;
624                 }
625         }
626         if (service) {
627                 entry->service = talloc_strdup(entry, service);
628                 if (!entry->service) {
629                         goto no_mem;
630                 }
631         }
632
633         entry->ccname = talloc_strdup(entry, ccname);
634         if (!entry->ccname) {
635                 goto no_mem;
636         }
637
638         entry->realm = talloc_strdup(entry, realm);
639         if (!entry->realm) {
640                 goto no_mem;
641         }
642
643         entry->create_time = create_time;
644         entry->renew_until = renew_until;
645         entry->uid = uid;
646         entry->ref_count = 1;
647
648         if (!lp_winbind_refresh_tickets() || renew_until <= 0) {
649                 goto add_entry;
650         }
651
652         if (postponed_request) {
653                 t = timeval_current_ofs(MAX(30, lp_winbind_cache_time()), 0);
654                 add_krb5_ticket_gain_handler_event(entry, t);
655         } else {
656                 /* Renew at 1/2 the ticket expiration time */
657 #if defined(DEBUG_KRB5_TKT_RENEWAL)
658                 t = timeval_set(time(NULL)+30, 0);
659 #else
660                 t = timeval_set(KRB5_EVENT_REFRESH_TIME(ticket_end), 0);
661 #endif
662                 if (entry->refresh_time == 0) {
663                         entry->refresh_time = t.tv_sec;
664                 }
665                 entry->event = event_add_timed(winbind_event_context(),
666                                                entry,
667                                                t,
668                                                krb5_ticket_refresh_handler,
669                                                entry);
670         }
671
672         if (!entry->event) {
673                 goto no_mem;
674         }
675
676         DEBUG(10,("add_ccache_to_list: added krb5_ticket handler\n"));
677
678  add_entry:
679
680         DLIST_ADD(ccache_list, entry);
681
682         DEBUG(10,("add_ccache_to_list: "
683                 "added ccache [%s] for user [%s] to the list\n",
684                 ccname, username));
685
686         if (entry->event) {
687                 /*
688                  * If we're set up to renew our krb5 tickets, we must
689                  * cache the credentials in memory for the ticket
690                  * renew function. Fix inspired by patch from
691                  * Ian Gordon <ian.gordon@strath.ac.uk> for
692                  * bugid #9098.
693                  */
694
695                 ntret = winbindd_add_memory_creds(username, uid, pass);
696                 DEBUG(10, ("winbindd_add_memory_creds returned: %s\n",
697                         nt_errstr(ntret)));
698         }
699
700         return NT_STATUS_OK;
701
702  no_mem:
703
704         TALLOC_FREE(entry);
705         return NT_STATUS_NO_MEMORY;
706 }
707
708 /*******************************************************************
709  Remove a WINBINDD_CCACHE_ENTRY entry and the krb5 ccache if no longer
710  referenced.
711  *******************************************************************/
712
713 NTSTATUS remove_ccache(const char *username)
714 {
715         struct WINBINDD_CCACHE_ENTRY *entry = get_ccache_by_username(username);
716         NTSTATUS status = NT_STATUS_OK;
717         #ifdef HAVE_KRB5
718         krb5_error_code ret;
719 #endif
720
721         if (!entry) {
722                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
723         }
724
725         if (entry->ref_count <= 0) {
726                 DEBUG(0,("remove_ccache: logic error. "
727                         "ref count for user %s = %d\n",
728                         username, entry->ref_count));
729                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
730         }
731
732         entry->ref_count--;
733
734         if (entry->ref_count > 0) {
735                 DEBUG(10,("remove_ccache: entry %s ref count now %d\n",
736                         username, entry->ref_count));
737                 return NT_STATUS_OK;
738         }
739
740         /* no references any more */
741
742         DLIST_REMOVE(ccache_list, entry);
743         TALLOC_FREE(entry->event); /* unregisters events */
744
745 #ifdef HAVE_KRB5
746         ret = ads_kdestroy(entry->ccname);
747
748         /* we ignore the error when there has been no credential cache */
749         if (ret == KRB5_FCC_NOFILE) {
750                 ret = 0;
751         } else if (ret) {
752                 DEBUG(0,("remove_ccache: "
753                         "failed to destroy user krb5 ccache %s with: %s\n",
754                         entry->ccname, error_message(ret)));
755         } else {
756                 DEBUG(10,("remove_ccache: "
757                         "successfully destroyed krb5 ccache %s for user %s\n",
758                         entry->ccname, username));
759         }
760         status = krb5_to_nt_status(ret);
761 #endif
762
763         TALLOC_FREE(entry);
764         DEBUG(10,("remove_ccache: removed ccache for user %s\n", username));
765
766         return status;
767 }
768
769 /*******************************************************************
770  In memory credentials cache code.
771 *******************************************************************/
772
773 static struct WINBINDD_MEMORY_CREDS *memory_creds_list;
774
775 /***********************************************************
776  Find an entry on the list by name.
777 ***********************************************************/
778
779 struct WINBINDD_MEMORY_CREDS *find_memory_creds_by_name(const char *username)
780 {
781         struct WINBINDD_MEMORY_CREDS *p;
782
783         for (p = memory_creds_list; p; p = p->next) {
784                 if (strequal(p->username, username)) {
785                         return p;
786                 }
787         }
788         return NULL;
789 }
790
791 /***********************************************************
792  Store the required creds and mlock them.
793 ***********************************************************/
794
795 static NTSTATUS store_memory_creds(struct WINBINDD_MEMORY_CREDS *memcredp,
796                                    const char *pass)
797 {
798 #if !defined(HAVE_MLOCK)
799         return NT_STATUS_OK;
800 #else
801         /* new_entry->nt_hash is the base pointer for the block
802            of memory pointed into by new_entry->lm_hash and
803            new_entry->pass (if we're storing plaintext). */
804
805         memcredp->len = NT_HASH_LEN + LM_HASH_LEN;
806         if (pass) {
807                 memcredp->len += strlen(pass)+1;
808         }
809
810
811 #if defined(LINUX)
812         /* aligning the memory on on x86_64 and compiling
813            with gcc 4.1 using -O2 causes a segv in the
814            next memset()  --jerry */
815         memcredp->nt_hash = SMB_MALLOC_ARRAY(unsigned char, memcredp->len);
816 #else
817         /* On non-linux platforms, mlock()'d memory must be aligned */
818         memcredp->nt_hash = SMB_MEMALIGN_ARRAY(unsigned char,
819                                                getpagesize(), memcredp->len);
820 #endif
821         if (!memcredp->nt_hash) {
822                 return NT_STATUS_NO_MEMORY;
823         }
824         memset(memcredp->nt_hash, 0x0, memcredp->len);
825
826         memcredp->lm_hash = memcredp->nt_hash + NT_HASH_LEN;
827
828 #ifdef DEBUG_PASSWORD
829         DEBUG(10,("mlocking memory: %p\n", memcredp->nt_hash));
830 #endif
831         if ((mlock(memcredp->nt_hash, memcredp->len)) == -1) {
832                 DEBUG(0,("failed to mlock memory: %s (%d)\n",
833                         strerror(errno), errno));
834                 SAFE_FREE(memcredp->nt_hash);
835                 return map_nt_error_from_unix(errno);
836         }
837
838 #ifdef DEBUG_PASSWORD
839         DEBUG(10,("mlocked memory: %p\n", memcredp->nt_hash));
840 #endif
841
842         /* Create and store the password hashes. */
843         E_md4hash(pass, memcredp->nt_hash);
844         E_deshash(pass, memcredp->lm_hash);
845
846         if (pass) {
847                 memcredp->pass = (char *)memcredp->lm_hash + LM_HASH_LEN;
848                 memcpy(memcredp->pass, pass,
849                        memcredp->len - NT_HASH_LEN - LM_HASH_LEN);
850         }
851
852         return NT_STATUS_OK;
853 #endif
854 }
855
856 /***********************************************************
857  Destroy existing creds.
858 ***********************************************************/
859
860 static NTSTATUS delete_memory_creds(struct WINBINDD_MEMORY_CREDS *memcredp)
861 {
862 #if !defined(HAVE_MUNLOCK)
863         return NT_STATUS_OK;
864 #else
865         if (munlock(memcredp->nt_hash, memcredp->len) == -1) {
866                 DEBUG(0,("failed to munlock memory: %s (%d)\n",
867                         strerror(errno), errno));
868                 return map_nt_error_from_unix(errno);
869         }
870         memset(memcredp->nt_hash, '\0', memcredp->len);
871         SAFE_FREE(memcredp->nt_hash);
872         memcredp->nt_hash = NULL;
873         memcredp->lm_hash = NULL;
874         memcredp->pass = NULL;
875         memcredp->len = 0;
876         return NT_STATUS_OK;
877 #endif
878 }
879
880 /***********************************************************
881  Replace the required creds with new ones (password change).
882 ***********************************************************/
883
884 static NTSTATUS winbindd_replace_memory_creds_internal(struct WINBINDD_MEMORY_CREDS *memcredp,
885                                                        const char *pass)
886 {
887         NTSTATUS status = delete_memory_creds(memcredp);
888         if (!NT_STATUS_IS_OK(status)) {
889                 return status;
890         }
891         return store_memory_creds(memcredp, pass);
892 }
893
894 /*************************************************************
895  Store credentials in memory in a list.
896 *************************************************************/
897
898 static NTSTATUS winbindd_add_memory_creds_internal(const char *username,
899                                                    uid_t uid,
900                                                    const char *pass)
901 {
902         /* Shortcut to ensure we don't store if no mlock. */
903 #if !defined(HAVE_MLOCK) || !defined(HAVE_MUNLOCK)
904         return NT_STATUS_OK;
905 #else
906         NTSTATUS status;
907         struct WINBINDD_MEMORY_CREDS *memcredp = NULL;
908
909         memcredp = find_memory_creds_by_name(username);
910         if (uid == (uid_t)-1) {
911                 DEBUG(0,("winbindd_add_memory_creds_internal: "
912                         "invalid uid for user %s.\n", username));
913                 return NT_STATUS_INVALID_PARAMETER;
914         }
915
916         if (memcredp) {
917                 /* Already exists. Increment the reference count and replace stored creds. */
918                 if (uid != memcredp->uid) {
919                         DEBUG(0,("winbindd_add_memory_creds_internal: "
920                                 "uid %u for user %s doesn't "
921                                 "match stored uid %u. Replacing.\n",
922                                 (unsigned int)uid, username,
923                                 (unsigned int)memcredp->uid));
924                         memcredp->uid = uid;
925                 }
926                 memcredp->ref_count++;
927                 DEBUG(10,("winbindd_add_memory_creds_internal: "
928                         "ref count for user %s is now %d\n",
929                         username, memcredp->ref_count));
930                 return winbindd_replace_memory_creds_internal(memcredp, pass);
931         }
932
933         memcredp = TALLOC_ZERO_P(NULL, struct WINBINDD_MEMORY_CREDS);
934         if (!memcredp) {
935                 return NT_STATUS_NO_MEMORY;
936         }
937         memcredp->username = talloc_strdup(memcredp, username);
938         if (!memcredp->username) {
939                 talloc_destroy(memcredp);
940                 return NT_STATUS_NO_MEMORY;
941         }
942
943         status = store_memory_creds(memcredp, pass);
944         if (!NT_STATUS_IS_OK(status)) {
945                 talloc_destroy(memcredp);
946                 return status;
947         }
948
949         memcredp->uid = uid;
950         memcredp->ref_count = 1;
951         DLIST_ADD(memory_creds_list, memcredp);
952
953         DEBUG(10,("winbindd_add_memory_creds_internal: "
954                 "added entry for user %s\n", username));
955
956         return NT_STATUS_OK;
957 #endif
958 }
959
960 /*************************************************************
961  Store users credentials in memory. If we also have a
962  struct WINBINDD_CCACHE_ENTRY for this username with a
963  refresh timer, then store the plaintext of the password
964  and associate the new credentials with the struct WINBINDD_CCACHE_ENTRY.
965 *************************************************************/
966
967 NTSTATUS winbindd_add_memory_creds(const char *username,
968                                    uid_t uid,
969                                    const char *pass)
970 {
971         struct WINBINDD_CCACHE_ENTRY *entry = get_ccache_by_username(username);
972         NTSTATUS status;
973
974         status = winbindd_add_memory_creds_internal(username, uid, pass);
975         if (!NT_STATUS_IS_OK(status)) {
976                 return status;
977         }
978
979         if (entry) {
980                 struct WINBINDD_MEMORY_CREDS *memcredp = NULL;
981                 memcredp = find_memory_creds_by_name(username);
982                 if (memcredp) {
983                         entry->cred_ptr = memcredp;
984                 }
985         }
986
987         return status;
988 }
989
990 /*************************************************************
991  Decrement the in-memory ref count - delete if zero.
992 *************************************************************/
993
994 NTSTATUS winbindd_delete_memory_creds(const char *username)
995 {
996         struct WINBINDD_MEMORY_CREDS *memcredp = NULL;
997         struct WINBINDD_CCACHE_ENTRY *entry = NULL;
998         NTSTATUS status = NT_STATUS_OK;
999
1000         memcredp = find_memory_creds_by_name(username);
1001         entry = get_ccache_by_username(username);
1002
1003         if (!memcredp) {
1004                 DEBUG(10,("winbindd_delete_memory_creds: unknown user %s\n",
1005                         username));
1006                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1007         }
1008
1009         if (memcredp->ref_count <= 0) {
1010                 DEBUG(0,("winbindd_delete_memory_creds: logic error. "
1011                         "ref count for user %s = %d\n",
1012                         username, memcredp->ref_count));
1013                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
1014         }
1015
1016         memcredp->ref_count--;
1017         if (memcredp->ref_count <= 0) {
1018                 delete_memory_creds(memcredp);
1019                 DLIST_REMOVE(memory_creds_list, memcredp);
1020                 talloc_destroy(memcredp);
1021                 DEBUG(10,("winbindd_delete_memory_creds: "
1022                         "deleted entry for user %s\n",
1023                         username));
1024         } else {
1025                 DEBUG(10,("winbindd_delete_memory_creds: "
1026                         "entry for user %s ref_count now %d\n",
1027                         username, memcredp->ref_count));
1028         }
1029
1030         if (entry) {
1031                 /* Ensure we have no dangling references to this. */
1032                 entry->cred_ptr = NULL;
1033         }
1034
1035         return status;
1036 }
1037
1038 /***********************************************************
1039  Replace the required creds with new ones (password change).
1040 ***********************************************************/
1041
1042 NTSTATUS winbindd_replace_memory_creds(const char *username,
1043                                        const char *pass)
1044 {
1045         struct WINBINDD_MEMORY_CREDS *memcredp = NULL;
1046
1047         memcredp = find_memory_creds_by_name(username);
1048         if (!memcredp) {
1049                 DEBUG(10,("winbindd_replace_memory_creds: unknown user %s\n",
1050                         username));
1051                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1052         }
1053
1054         DEBUG(10,("winbindd_replace_memory_creds: replaced creds for user %s\n",
1055                 username));
1056
1057         return winbindd_replace_memory_creds_internal(memcredp, pass);
1058 }