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