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