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