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