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