s3:events: change event_add_timed() prototype to match samba4
[obnox/samba-ctdb.git] / source3 / winbindd / winbindd_cred_cache.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    Winbind daemon - krb5 credential cache functions
5    and in-memory cache functions.
6
7    Copyright (C) Guenther Deschner 2005-2006
8    Copyright (C) Jeremy Allison 2006
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "includes.h"
25 #include "winbindd.h"
26 #undef DBGC_CLASS
27 #define DBGC_CLASS DBGC_WINBIND
28
29 /* uncomment this to do fast debugging on the krb5 ticket renewal event */
30 #ifdef DEBUG_KRB5_TKT_RENEWAL
31 #undef DEBUG_KRB5_TKT_RENEWAL
32 #endif
33
34 #define MAX_CCACHES 100
35
36 static struct WINBINDD_CCACHE_ENTRY *ccache_list;
37 static void krb5_ticket_gain_handler(struct event_context *,
38                                      struct timed_event *,
39                                      struct timeval,
40                                      void *);
41
42 /* The Krb5 ticket refresh handler should be scheduled
43    at one-half of the period from now till the tkt
44    expiration */
45 #define KRB5_EVENT_REFRESH_TIME(x) ((x) - (((x) - time(NULL))/2))
46
47 /****************************************************************
48  Find an entry by name.
49 ****************************************************************/
50
51 static struct WINBINDD_CCACHE_ENTRY *get_ccache_by_username(const char *username)
52 {
53         struct WINBINDD_CCACHE_ENTRY *entry;
54
55         for (entry = ccache_list; entry; entry = entry->next) {
56                 if (strequal(entry->username, username)) {
57                         return entry;
58                 }
59         }
60         return NULL;
61 }
62
63 /****************************************************************
64  How many do we have ?
65 ****************************************************************/
66
67 static int ccache_entry_count(void)
68 {
69         struct WINBINDD_CCACHE_ENTRY *entry;
70         int i = 0;
71
72         for (entry = ccache_list; entry; entry = entry->next) {
73                 i++;
74         }
75         return i;
76 }
77
78 void ccache_remove_all_after_fork(void)
79 {
80         struct WINBINDD_CCACHE_ENTRY *cur, *next;
81
82         for (cur = ccache_list; cur; cur = next) {
83                 next = cur->next;
84                 DLIST_REMOVE(ccache_list, cur);
85                 TALLOC_FREE(cur->event);
86                 TALLOC_FREE(cur);
87         }
88
89         return;
90 }
91
92 /****************************************************************
93  Do the work of refreshing the ticket.
94 ****************************************************************/
95
96 static void krb5_ticket_refresh_handler(struct event_context *event_ctx,
97                                         struct timed_event *te,
98                                         struct timeval now,
99                                         void *private_data)
100 {
101         struct WINBINDD_CCACHE_ENTRY *entry =
102                 talloc_get_type_abort(private_data, struct WINBINDD_CCACHE_ENTRY);
103 #ifdef HAVE_KRB5
104         int ret;
105         time_t new_start;
106         time_t expire_time = 0;
107         struct WINBINDD_MEMORY_CREDS *cred_ptr = entry->cred_ptr;
108 #endif
109
110         DEBUG(10,("krb5_ticket_refresh_handler called\n"));
111         DEBUGADD(10,("event called for: %s, %s\n",
112                 entry->ccname, entry->username));
113
114         TALLOC_FREE(entry->event);
115
116 #ifdef HAVE_KRB5
117
118         /* Kinit again if we have the user password and we can't renew the old
119          * tgt anymore 
120          * NB
121          * This happens when machine are put to sleep for a very long time. */
122
123         if (entry->renew_until < time(NULL)) {
124 rekinit:
125                 if (cred_ptr && cred_ptr->pass) {
126
127                         set_effective_uid(entry->uid);
128
129                         ret = kerberos_kinit_password_ext(entry->principal_name,
130                                                           cred_ptr->pass,
131                                                           0, /* hm, can we do time correction here ? */
132                                                           &entry->refresh_time,
133                                                           &entry->renew_until,
134                                                           entry->ccname,
135                                                           False, /* no PAC required anymore */
136                                                           True,
137                                                           WINBINDD_PAM_AUTH_KRB5_RENEW_TIME,
138                                                           NULL);
139                         gain_root_privilege();
140
141                         if (ret) {
142                                 DEBUG(3,("krb5_ticket_refresh_handler: "
143                                         "could not re-kinit: %s\n",
144                                         error_message(ret)));
145                                 /* destroy the ticket because we cannot rekinit
146                                  * it, ignore error here */
147                                 ads_kdestroy(entry->ccname);
148
149                                 /* Don't break the ticket refresh chain: retry 
150                                  * refreshing ticket sometime later when KDC is 
151                                  * unreachable -- BoYang 
152                                  * */
153
154                                 if ((ret == KRB5_KDC_UNREACH)
155                                     || (ret == KRB5_REALM_CANT_RESOLVE)) {
156 #if defined(DEBUG_KRB5_TKT_RENEWAL)
157                                         new_start = time(NULL) + 30;
158 #else
159                                         new_start = time(NULL) +
160                                                     MAX(30, lp_winbind_cache_time());
161 #endif
162                                         /* try to regain ticket here */
163                                         entry->event = event_add_timed(winbind_event_context(),
164                                                                        entry, 
165                                                                        timeval_set(new_start, 0),
166                                                                        krb5_ticket_gain_handler,
167                                                                        entry);
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
231                 if ((ret == KRB5_KDC_UNREACH) 
232                     || (ret == KRB5_REALM_CANT_RESOLVE)) {
233 #if defined(DEBUG_KRB5_TKT_RENEWAL)
234                         new_start = time(NULL) + 30;
235 #else
236                         new_start = time(NULL) +
237                                     MAX(30, lp_winbind_cache_time());
238 #endif
239                         /* ticket is destroyed here, we have to regain it
240                          * if it is possible */
241                         entry->event = event_add_timed(winbind_event_context(),
242                                                         entry,
243                                                         timeval_set(new_start, 0),
244                                                         krb5_ticket_gain_handler,
245                                                         entry);
246                         return;
247                 }
248
249                 /* This is evil, if the ticket was already expired.
250                  * renew ticket function returns KRB5KRB_AP_ERR_TKT_EXPIRED.
251                  * But there is still a chance that we can rekinit it. 
252                  *
253                  * This happens when user login in online mode, and then network
254                  * down or something cause winbind goes offline for a very long time,
255                  * and then goes online again. ticket expired, renew failed.
256                  * This happens when machine are put to sleep for a long time,
257                  * but shorter than entry->renew_util.
258                  * NB
259                  * Looks like the KDC is reachable, we want to rekinit as soon as
260                  * possible instead of waiting some time later. */
261                 if ((ret == KRB5KRB_AP_ERR_TKT_EXPIRED)
262                     || (ret == KRB5_FCC_NOFILE)) goto rekinit;
263
264                 return;
265         }
266
267 done:
268         /* in cases that ticket will be unrenewable soon, we don't try to renew ticket 
269          * but try to regain ticket if it is possible */
270         if (entry->renew_until && expire_time
271              && (entry->renew_until <= expire_time)) {
272                 /* try to regain ticket 10 seconds beforre expiration */
273                 expire_time -= 10;
274                 entry->event = event_add_timed(winbind_event_context(), entry,
275                                                 timeval_set(expire_time, 0),
276                                                 krb5_ticket_gain_handler,
277                                                 entry);
278                 return;
279         }
280
281         if (entry->refresh_time == 0) {
282                 entry->refresh_time = new_start;
283         }
284         entry->event = event_add_timed(winbind_event_context(), entry,
285                                        timeval_set(new_start, 0),
286                                        krb5_ticket_refresh_handler,
287                                        entry);
288
289 #endif
290 }
291
292 /****************************************************************
293  Do the work of regaining a ticket when coming from offline auth.
294 ****************************************************************/
295
296 static void krb5_ticket_gain_handler(struct event_context *event_ctx,
297                                      struct timed_event *te,
298                                      struct timeval now,
299                                      void *private_data)
300 {
301         struct WINBINDD_CCACHE_ENTRY *entry =
302                 talloc_get_type_abort(private_data, struct WINBINDD_CCACHE_ENTRY);
303 #ifdef HAVE_KRB5
304         int ret;
305         struct timeval t;
306         struct WINBINDD_MEMORY_CREDS *cred_ptr = entry->cred_ptr;
307         struct winbindd_domain *domain = NULL;
308 #endif
309
310         DEBUG(10,("krb5_ticket_gain_handler called\n"));
311         DEBUGADD(10,("event called for: %s, %s\n",
312                 entry->ccname, entry->username));
313
314         TALLOC_FREE(entry->event);
315
316 #ifdef HAVE_KRB5
317
318         if (!cred_ptr || !cred_ptr->pass) {
319                 DEBUG(10,("krb5_ticket_gain_handler: no memory creds\n"));
320                 return;
321         }
322
323         if ((domain = find_domain_from_name(entry->realm)) == NULL) {
324                 DEBUG(0,("krb5_ticket_gain_handler: unknown domain\n"));
325                 return;
326         }
327
328         if (!domain->online) {
329                 goto retry_later;
330         }
331
332         set_effective_uid(entry->uid);
333
334         ret = kerberos_kinit_password_ext(entry->principal_name,
335                                           cred_ptr->pass,
336                                           0, /* hm, can we do time correction here ? */
337                                           &entry->refresh_time,
338                                           &entry->renew_until,
339                                           entry->ccname,
340                                           False, /* no PAC required anymore */
341                                           True,
342                                           WINBINDD_PAM_AUTH_KRB5_RENEW_TIME,
343                                           NULL);
344         gain_root_privilege();
345
346         if (ret) {
347                 DEBUG(3,("krb5_ticket_gain_handler: "
348                         "could not kinit: %s\n",
349                         error_message(ret)));
350                 /* evil. If we cannot do it, destroy any the __maybe__ 
351                  * __existing__ ticket */
352                 ads_kdestroy(entry->ccname);
353                 goto retry_later;
354         }
355
356         DEBUG(10,("krb5_ticket_gain_handler: "
357                 "successful kinit for: %s in ccache: %s\n",
358                 entry->principal_name, entry->ccname));
359
360         goto got_ticket;
361
362   retry_later:
363  
364 #if defined(DEBUG_KRB5_TKT_REGAIN)
365         t = timeval_set(time(NULL) + 30, 0);
366 #else
367         t = timeval_current_ofs(MAX(30, lp_winbind_cache_time()), 0);
368 #endif
369
370         entry->refresh_time = 0;
371         entry->event = event_add_timed(winbind_event_context(),
372                                        entry,
373                                        t,
374                                        krb5_ticket_gain_handler,
375                                        entry);
376
377         return;
378
379   got_ticket:
380
381 #if defined(DEBUG_KRB5_TKT_RENEWAL)
382         t = timeval_set(time(NULL) + 30, 0);
383 #else
384         t = timeval_set(KRB5_EVENT_REFRESH_TIME(entry->refresh_time), 0);
385 #endif
386
387         if (entry->refresh_time == 0) {
388                 entry->refresh_time = t.tv_sec;
389         }
390         entry->event = event_add_timed(winbind_event_context(),
391                                        entry,
392                                        t,
393                                        krb5_ticket_refresh_handler,
394                                        entry);
395
396         return;
397 #endif
398 }
399
400 void ccache_regain_all_now(void)
401 {
402         struct WINBINDD_CCACHE_ENTRY *cur;
403         struct timeval t = timeval_current();
404
405         for (cur = ccache_list; cur; cur = cur->next) {
406                 struct timed_event *new_event;
407
408                 /*
409                  * if refresh_time is 0, we know that the
410                  * the event has the krb5_ticket_gain_handler
411                  */
412                 if (cur->refresh_time == 0) {
413                         new_event = event_add_timed(winbind_event_context(),
414                                                     cur,
415                                                     t,
416                                                     krb5_ticket_gain_handler,
417                                                     cur);
418                 } else {
419                         new_event = event_add_timed(winbind_event_context(),
420                                                     cur,
421                                                     t,
422                                                     krb5_ticket_refresh_handler,
423                                                     cur);
424                 }
425
426                 if (!new_event) {
427                         continue;
428                 }
429
430                 TALLOC_FREE(cur->event);
431                 cur->event = new_event;
432         }
433
434         return;
435 }
436
437 /****************************************************************
438  Check if an ccache entry exists.
439 ****************************************************************/
440
441 bool ccache_entry_exists(const char *username)
442 {
443         struct WINBINDD_CCACHE_ENTRY *entry = get_ccache_by_username(username);
444         return (entry != NULL);
445 }
446
447 /****************************************************************
448  Ensure we're changing the correct entry.
449 ****************************************************************/
450
451 bool ccache_entry_identical(const char *username,
452                             uid_t uid,
453                             const char *ccname)
454 {
455         struct WINBINDD_CCACHE_ENTRY *entry = get_ccache_by_username(username);
456
457         if (!entry) {
458                 return False;
459         }
460
461         if (entry->uid != uid) {
462                 DEBUG(0,("cache_entry_identical: uid's differ: %u != %u\n",
463                         (unsigned int)entry->uid, (unsigned int)uid));
464                 return False;
465         }
466         if (!strcsequal(entry->ccname, ccname)) {
467                 DEBUG(0,("cache_entry_identical: "
468                         "ccnames differ: (cache) %s != (client) %s\n",
469                         entry->ccname, ccname));
470                 return False;
471         }
472         return True;
473 }
474
475 NTSTATUS add_ccache_to_list(const char *princ_name,
476                             const char *ccname,
477                             const char *service,
478                             const char *username,
479                             const char *realm,
480                             uid_t uid,
481                             time_t create_time,
482                             time_t ticket_end,
483                             time_t renew_until,
484                             bool postponed_request)
485 {
486         struct WINBINDD_CCACHE_ENTRY *entry = NULL;
487         struct timeval t;
488         NTSTATUS ntret;
489 #ifdef HAVE_KRB5
490         int ret;
491 #endif
492
493         if ((username == NULL && princ_name == NULL) ||
494             ccname == NULL || uid < 0) {
495                 return NT_STATUS_INVALID_PARAMETER;
496         }
497
498         if (ccache_entry_count() + 1 > MAX_CCACHES) {
499                 DEBUG(10,("add_ccache_to_list: "
500                         "max number of ccaches reached\n"));
501                 return NT_STATUS_NO_MORE_ENTRIES;
502         }
503
504         /* If it is cached login, destroy krb5 ticket
505          * to avoid surprise. */
506 #ifdef HAVE_KRB5
507         if (postponed_request) {
508                 /* ignore KRB5_FCC_NOFILE error here */
509                 ret = ads_kdestroy(ccname);
510                 if (ret == KRB5_FCC_NOFILE) {
511                         ret = 0;
512                 }
513                 if (ret) {
514                         DEBUG(0, ("add_ccache_to_list: failed to destroy "
515                                    "user krb5 ccache %s with %s\n", ccname,
516                                    error_message(ret)));
517                         return krb5_to_nt_status(ret);
518                 } else {
519                         DEBUG(10, ("add_ccache_to_list: successfully destroyed "
520                                    "krb5 ccache %s for user %s\n", ccname,
521                                    username));
522                 }
523         }
524 #endif
525
526         /* Reference count old entries */
527         entry = get_ccache_by_username(username);
528         if (entry) {
529                 /* Check cached entries are identical. */
530                 if (!ccache_entry_identical(username, uid, ccname)) {
531                         return NT_STATUS_INVALID_PARAMETER;
532                 }
533                 entry->ref_count++;
534                 DEBUG(10,("add_ccache_to_list: "
535                         "ref count on entry %s is now %d\n",
536                         username, entry->ref_count));
537                 /* FIXME: in this case we still might want to have a krb5 cred
538                  * event handler created - gd
539                  * Add ticket refresh handler here */
540                 
541                 if (!lp_winbind_refresh_tickets() || renew_until <= 0) {
542                         return NT_STATUS_OK;
543                 }
544                 
545                 if (!entry->event) {
546                         if (postponed_request) {
547                                 t = timeval_current_ofs(MAX(30, lp_winbind_cache_time()), 0);
548                                 entry->event = event_add_timed(winbind_event_context(),
549                                                                entry,
550                                                                t,
551                                                                krb5_ticket_gain_handler,
552                                                                entry);
553                         } else {
554                                 /* Renew at 1/2 the ticket expiration time */
555 #if defined(DEBUG_KRB5_TKT_RENEWAL)
556                                 t = timeval_set(time(NULL)+30, 0);
557 #else
558                                 t = timeval_set(KRB5_EVENT_REFRESH_TIME(ticket_end), 0);
559 #endif
560                                 entry->event = event_add_timed(winbind_event_context(),
561                                                                entry,
562                                                                t,
563                                                                krb5_ticket_refresh_handler,
564                                                                entry);
565                         }
566
567                         if (!entry->event) {
568                                 ntret = remove_ccache(username);
569                                 if (!NT_STATUS_IS_OK(ntret)) {
570                                         DEBUG(0, ("add_ccache_to_list: Failed to remove krb5 "
571                                                   "ccache %s for user %s\n", entry->ccname,
572                                                   entry->username));
573                                         DEBUG(0, ("add_ccache_to_list: error is %s\n",
574                                                   nt_errstr(ntret)));
575                                         return ntret;
576                                 }
577                                 return NT_STATUS_NO_MEMORY;
578                         }
579
580                         DEBUG(10,("add_ccache_to_list: added krb5_ticket handler\n"));
581                 }
582                  
583                 return NT_STATUS_OK;
584         }
585
586         entry = TALLOC_P(NULL, struct WINBINDD_CCACHE_ENTRY);
587         if (!entry) {
588                 return NT_STATUS_NO_MEMORY;
589         }
590
591         ZERO_STRUCTP(entry);
592
593         if (username) {
594                 entry->username = talloc_strdup(entry, username);
595                 if (!entry->username) {
596                         goto no_mem;
597                 }
598         }
599         if (princ_name) {
600                 entry->principal_name = talloc_strdup(entry, princ_name);
601                 if (!entry->principal_name) {
602                         goto no_mem;
603                 }
604         }
605         if (service) {
606                 entry->service = talloc_strdup(entry, service);
607                 if (!entry->service) {
608                         goto no_mem;
609                 }
610         }
611
612         entry->ccname = talloc_strdup(entry, ccname);
613         if (!entry->ccname) {
614                 goto no_mem;
615         }
616
617         entry->realm = talloc_strdup(entry, realm);
618         if (!entry->realm) {
619                 goto no_mem;
620         }
621
622         entry->create_time = create_time;
623         entry->renew_until = renew_until;
624         entry->uid = uid;
625         entry->ref_count = 1;
626
627         if (!lp_winbind_refresh_tickets() || renew_until <= 0) {
628                 goto add_entry;
629         }
630
631         if (postponed_request) {
632                 t = timeval_current_ofs(MAX(30, lp_winbind_cache_time()), 0);
633                 entry->refresh_time = 0;
634                 entry->event = event_add_timed(winbind_event_context(),
635                                                entry,
636                                                t,
637                                                krb5_ticket_gain_handler,
638                                                entry);
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 }