]> git.decadent.org.uk Git - nfs-utils.git/blob - utils/gssd/krb5_util.c
Add option to allow root to use credentials other than machine credentials
[nfs-utils.git] / utils / gssd / krb5_util.c
1 /*
2  *  Adapted in part from MIT Kerberos 5-1.2.1 slave/kprop.c and from
3  *  http://docs.sun.com/?p=/doc/816-1331/6m7oo9sms&a=view
4  *
5  *  Copyright (c) 2002-2004 The Regents of the University of Michigan.
6  *  All rights reserved.
7  *
8  *  Andy Adamson <andros@umich.edu>
9  *  J. Bruce Fields <bfields@umich.edu>
10  *  Marius Aamodt Eriksen <marius@umich.edu>
11  *  Kevin Coffman <kwc@umich.edu>
12  */
13
14 /*
15  * slave/kprop.c
16  *
17  * Copyright 1990,1991 by the Massachusetts Institute of Technology.
18  * All Rights Reserved.
19  *
20  * Export of this software from the United States of America may
21  *   require a specific license from the United States Government.
22  *   It is the responsibility of any person or organization contemplating
23  *   export to obtain such a license before exporting.
24  *
25  * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
26  * distribute this software and its documentation for any purpose and
27  * without fee is hereby granted, provided that the above copyright
28  * notice appear in all copies and that both that copyright notice and
29  * this permission notice appear in supporting documentation, and that
30  * the name of M.I.T. not be used in advertising or publicity pertaining
31  * to distribution of the software without specific, written prior
32  * permission.  Furthermore if you modify this software you must label
33  * your software as modified software and not distribute it in such a
34  * fashion that it might be confused with the original M.I.T. software.
35  * M.I.T. makes no representations about the suitability of
36  * this software for any purpose.  It is provided "as is" without express
37  * or implied warranty.
38  */
39
40 /*
41  * Copyright 1994 by OpenVision Technologies, Inc.
42  *
43  * Permission to use, copy, modify, distribute, and sell this software
44  * and its documentation for any purpose is hereby granted without fee,
45  * provided that the above copyright notice appears in all copies and
46  * that both that copyright notice and this permission notice appear in
47  * supporting documentation, and that the name of OpenVision not be used
48  * in advertising or publicity pertaining to distribution of the software
49  * without specific, written prior permission. OpenVision makes no
50  * representations about the suitability of this software for any
51  * purpose.  It is provided "as is" without express or implied warranty.
52  *
53  * OPENVISION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
54  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
55  * EVENT SHALL OPENVISION BE LIABLE FOR ANY SPECIAL, INDIRECT OR
56  * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
57  * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
58  * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
59  * PERFORMANCE OF THIS SOFTWARE.
60  */
61 /*
62   krb5_util.c
63
64   Copyright (c) 2004 The Regents of the University of Michigan.
65   All rights reserved.
66
67   Redistribution and use in source and binary forms, with or without
68   modification, are permitted provided that the following conditions
69   are met:
70
71   1. Redistributions of source code must retain the above copyright
72      notice, this list of conditions and the following disclaimer.
73   2. Redistributions in binary form must reproduce the above copyright
74      notice, this list of conditions and the following disclaimer in the
75      documentation and/or other materials provided with the distribution.
76   3. Neither the name of the University nor the names of its
77      contributors may be used to endorse or promote products derived
78      from this software without specific prior written permission.
79
80   THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
81   WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
82   MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
83   DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
84   FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
85   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
86   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
87   BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
88   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
89   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
90   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
91
92 */
93
94 #ifndef _GNU_SOURCE
95 #define _GNU_SOURCE
96 #endif
97 #include "config.h"
98 #include <sys/param.h>
99 #include <rpc/rpc.h>
100 #include <sys/stat.h>
101 #include <sys/socket.h>
102 #include <arpa/inet.h>
103
104 #include <stdio.h>
105 #include <stdlib.h>
106 #include <string.h>
107 #include <dirent.h>
108 #include <errno.h>
109 #include <time.h>
110 #include <gssapi/gssapi.h>
111 #ifdef USE_PRIVATE_KRB5_FUNCTIONS
112 #include <gssapi/gssapi_krb5.h>
113 #endif
114 #include <krb5.h>
115 #include <rpc/auth_gss.h>
116
117 #include "gssd.h"
118 #include "err_util.h"
119 #include "gss_util.h"
120 #include "gss_oids.h"
121 #include "krb5_util.h"
122
123 /* Global list of principals/cache file names for machine credentials */
124 struct gssd_k5_kt_princ *gssd_k5_kt_princ_list = NULL;
125
126 /*==========================*/
127 /*===  Internal routines ===*/
128 /*==========================*/
129
130 static int select_krb5_ccache(const struct dirent *d);
131 static int gssd_find_existing_krb5_ccache(uid_t uid, struct dirent **d);
132 static int gssd_get_single_krb5_cred(krb5_context context,
133                 krb5_keytab kt, struct gssd_k5_kt_princ *ple);
134 static int gssd_have_realm_ple(void *realm);
135 static int gssd_process_krb5_keytab(krb5_context context, krb5_keytab kt,
136                 char *kt_name);
137
138 /*
139  * Called from the scandir function to weed out potential krb5
140  * credentials cache files
141  *
142  * Returns:
143  *      0 => don't select this one
144  *      1 => select this one
145  */
146 static int
147 select_krb5_ccache(const struct dirent *d)
148 {
149         /*
150          * Note: We used to check d->d_type for DT_REG here,
151          * but apparenlty reiser4 always has DT_UNKNOWN.
152          * Check for IS_REG after stat() call instead.
153          */
154         if (strstr(d->d_name, GSSD_DEFAULT_CRED_PREFIX))
155                 return 1;
156         else
157                 return 0;
158 }
159
160 /*
161  * Look in the ccachedir for files that look like they
162  * are Kerberos Credential Cache files for a given UID.  Return
163  * non-zero and the dirent pointer for the entry most likely to be
164  * what we want. Otherwise, return zero and no dirent pointer.
165  * The caller is responsible for freeing the dirent if one is returned.
166  *
167  * Returns:
168  *      0 => could not find an existing entry
169  *      1 => found an existing entry
170  */
171 static int
172 gssd_find_existing_krb5_ccache(uid_t uid, struct dirent **d)
173 {
174         struct dirent **namelist;
175         int n;
176         int i;
177         int found = 0;
178         struct dirent *best_match_dir = NULL;
179         struct stat best_match_stat, tmp_stat;
180
181         memset(&best_match_stat, 0, sizeof(best_match_stat));
182         *d = NULL;
183         n = scandir(ccachedir, &namelist, select_krb5_ccache, 0);
184         if (n < 0) {
185                 perror("scandir looking for krb5 credentials caches");
186         }
187         else if (n > 0) {
188                 char statname[1024];
189                 for (i = 0; i < n; i++) {
190                         printerr(3, "CC file '%s' being considered\n",
191                                  namelist[i]->d_name);
192                         snprintf(statname, sizeof(statname),
193                                  "%s/%s", ccachedir, namelist[i]->d_name);
194                         if (lstat(statname, &tmp_stat)) {
195                                 printerr(0, "Error doing stat on file '%s'\n",
196                                          statname);
197                                 free(namelist[i]);
198                                 continue;
199                         }
200                         /* Only pick caches owned by the user (uid) */
201                         if (tmp_stat.st_uid != uid) {
202                                 printerr(3, "'%s' owned by %u, not %u\n",
203                                          statname, tmp_stat.st_uid, uid);
204                                 free(namelist[i]);
205                                 continue;
206                         }
207                         if (!S_ISREG(tmp_stat.st_mode)) {
208                                 printerr(3, "'%s' is not a regular file\n",
209                                          statname);
210                                 free(namelist[i]);
211                                 continue;
212                         }
213                         printerr(3, "CC file '%s' matches owner check and has "
214                                  "mtime of %u\n",
215                                  namelist[i]->d_name, tmp_stat.st_mtime);
216                         /*
217                          * if more than one match is found, return the most
218                          * recent (the one with the latest mtime), and
219                          * don't free the dirent
220                          */
221                         if (!found) {
222                                 best_match_dir = namelist[i];
223                                 best_match_stat = tmp_stat;
224                                 found++;
225                         }
226                         else {
227                                 /*
228                                  * If the current match has an mtime later
229                                  * than the one we are looking at, then use
230                                  * the current match.  Otherwise, we still
231                                  * have the best match.
232                                  */
233                                 if (tmp_stat.st_mtime >
234                                             best_match_stat.st_mtime) {
235                                         free(best_match_dir);
236                                         best_match_dir = namelist[i];
237                                         best_match_stat = tmp_stat;
238                                 }
239                                 else {
240                                         free(namelist[i]);
241                                 }
242                                 printerr(3, "CC file '%s' is our "
243                                             "current best match "
244                                             "with mtime of %u\n",
245                                          best_match_dir->d_name,
246                                          best_match_stat.st_mtime);
247                         }
248                 }
249                 free(namelist);
250         }
251         if (found)
252         {
253                 *d = best_match_dir;
254         }
255         return found;
256 }
257
258
259 #ifdef HAVE_SET_ALLOWABLE_ENCTYPES
260 /*
261  * this routine obtains a credentials handle via gss_acquire_cred()
262  * then calls gss_krb5_set_allowable_enctypes() to limit the encryption
263  * types negotiated.
264  *
265  * XXX Should call some function to determine the enctypes supported
266  * by the kernel. (Only need to do that once!)
267  *
268  * Returns:
269  *      0 => all went well
270  *     -1 => there was an error
271  */
272
273 int
274 limit_krb5_enctypes(struct rpc_gss_sec *sec, uid_t uid)
275 {
276         u_int maj_stat, min_stat;
277         gss_cred_id_t credh;
278         gss_OID_set_desc  desired_mechs;
279         krb5_enctype enctypes[] = { ENCTYPE_DES_CBC_CRC };
280         int num_enctypes = sizeof(enctypes) / sizeof(enctypes[0]);
281
282         /* We only care about getting a krb5 cred */
283         desired_mechs.count = 1;
284         desired_mechs.elements = &krb5oid;
285
286         maj_stat = gss_acquire_cred(&min_stat, NULL, 0,
287                                     &desired_mechs, GSS_C_INITIATE,
288                                     &credh, NULL, NULL);
289
290         if (maj_stat != GSS_S_COMPLETE) {
291                 pgsserr("gss_acquire_cred",
292                         maj_stat, min_stat, &krb5oid);
293                 return -1;
294         }
295
296         maj_stat = gss_set_allowable_enctypes(&min_stat, credh, &krb5oid,
297                                              num_enctypes, &enctypes);
298         if (maj_stat != GSS_S_COMPLETE) {
299                 pgsserr("gss_set_allowable_enctypes",
300                         maj_stat, min_stat, &krb5oid);
301                 return -1;
302         }
303         sec->cred = credh;
304
305         return 0;
306 }
307 #endif  /* HAVE_SET_ALLOWABLE_ENCTYPES */
308
309 /*
310  * Obtain credentials via a key in the keytab given
311  * a keytab handle and a gssd_k5_kt_princ structure.
312  * Checks to see if current credentials are expired,
313  * if not, uses the keytab to obtain new credentials.
314  *
315  * Returns:
316  *      0 => success (or credentials have not expired)
317  *      nonzero => error
318  */
319 static int
320 gssd_get_single_krb5_cred(krb5_context context,
321                           krb5_keytab kt,
322                           struct gssd_k5_kt_princ *ple)
323 {
324         krb5_get_init_creds_opt options;
325         krb5_creds my_creds;
326         krb5_ccache ccache = NULL;
327         char kt_name[BUFSIZ];
328         char cc_name[BUFSIZ];
329         int code;
330         time_t now = time(0);
331         char *cache_type;
332
333         memset(&my_creds, 0, sizeof(my_creds));
334
335         if (ple->ccname && ple->endtime > now) {
336                 printerr(2, "INFO: Credentials in CC '%s' are good until %d\n",
337                          ple->ccname, ple->endtime);
338                 code = 0;
339                 goto out;
340         }
341
342         if ((code = krb5_kt_get_name(context, kt, kt_name, BUFSIZ))) {
343                 printerr(0, "ERROR: Unable to get keytab name in "
344                             "gssd_get_single_krb5_cred\n");
345                 goto out;
346         }
347
348         krb5_get_init_creds_opt_init(&options);
349         krb5_get_init_creds_opt_set_address_list(&options, NULL);
350
351 #ifdef TEST_SHORT_LIFETIME
352         /* set a short lifetime (for debugging only!) */
353         printerr(0, "WARNING: Using (debug) short machine cred lifetime!\n");
354         krb5_get_init_creds_opt_set_tkt_life(&options, 5*60);
355 #endif
356         if ((code = krb5_get_init_creds_keytab(context, &my_creds, ple->princ,
357                                           kt, 0, NULL, &options))) {
358                 char *pname;
359                 if ((krb5_unparse_name(context, ple->princ, &pname))) {
360                         pname = NULL;
361                 }
362                 printerr(0, "WARNING: %s while getting initial ticket for "
363                             "principal '%s' from keytab '%s'\n",
364                          error_message(code),
365                          pname ? pname : "<unparsable>", kt_name);
366 #ifdef HAVE_KRB5
367                 if (pname) krb5_free_unparsed_name(context, pname);
368 #else
369                 if (pname) free(pname);
370 #endif
371                 goto out;
372         }
373
374         /*
375          * Initialize cache file which we're going to be using
376          */
377
378         if (use_memcache)
379             cache_type = "MEMORY";
380         else
381             cache_type = "FILE";
382         snprintf(cc_name, sizeof(cc_name), "%s:%s/%s%s_%s",
383                 cache_type,
384                 GSSD_DEFAULT_CRED_DIR, GSSD_DEFAULT_CRED_PREFIX,
385                 GSSD_DEFAULT_MACHINE_CRED_SUFFIX, ple->realm);
386         ple->endtime = my_creds.times.endtime;
387         ple->ccname = strdup(cc_name);
388         if (ple->ccname == NULL) {
389                 printerr(0, "ERROR: no storage to duplicate credentials "
390                             "cache name\n");
391                 code = ENOMEM;
392                 goto out;
393         }
394         if ((code = krb5_cc_resolve(context, cc_name, &ccache))) {
395                 printerr(0, "ERROR: %s while opening credential cache '%s'\n",
396                          error_message(code), cc_name);
397                 goto out;
398         }
399         if ((code = krb5_cc_initialize(context, ccache, ple->princ))) {
400                 printerr(0, "ERROR: %s while initializing credential "
401                          "cache '%s'\n", error_message(code), cc_name);
402                 goto out;
403         }
404         if ((code = krb5_cc_store_cred(context, ccache, &my_creds))) {
405                 printerr(0, "ERROR: %s while storing credentials in '%s'\n",
406                          error_message(code), cc_name);
407                 goto out;
408         }
409
410         code = 0;
411         printerr(1, "Using (machine) credentials cache: '%s'\n", cc_name);
412   out:
413         if (ccache)
414                 krb5_cc_close(context, ccache);
415         krb5_free_cred_contents(context, &my_creds);
416         return (code);
417 }
418
419 /*
420  * Determine if we already have a ple for the given realm
421  *
422  * Returns:
423  *      0 => no ple found for given realm
424  *      1 => found ple for given realm
425  */
426 static int
427 gssd_have_realm_ple(void *r)
428 {
429         struct gssd_k5_kt_princ *ple;
430 #ifdef HAVE_KRB5
431         krb5_data *realm = (krb5_data *)r;
432 #else
433         char *realm = (char *)r;
434 #endif
435
436         for (ple = gssd_k5_kt_princ_list; ple; ple = ple->next) {
437 #ifdef HAVE_KRB5
438                 if ((realm->length == strlen(ple->realm)) &&
439                     (strncmp(realm->data, ple->realm, realm->length) == 0)) {
440 #else
441                 if (strcmp(realm, ple->realm) == 0) {
442 #endif
443                     return 1;
444                 }
445         }
446         return 0;
447 }
448
449 /*
450  * Process the given keytab file and create a list of principals we
451  * might use to perform mount operations.
452  *
453  * Returns:
454  *      0 => Sucess
455  *      nonzero => Error
456  */
457 static int
458 gssd_process_krb5_keytab(krb5_context context, krb5_keytab kt, char *kt_name)
459 {
460         krb5_kt_cursor cursor;
461         krb5_keytab_entry kte;
462         krb5_error_code code;
463         struct gssd_k5_kt_princ *ple;
464         int retval = -1;
465
466         /*
467          * Look through each entry in the keytab file and determine
468          * if we might want to use it later to do a mount.  If so,
469          * save info in the global principal list
470          * (gssd_k5_kt_princ_list).
471          * Note: (ple == principal list entry)
472          */
473         if ((code = krb5_kt_start_seq_get(context, kt, &cursor))) {
474                 printerr(0, "ERROR: %s while beginning keytab scan "
475                             "for keytab '%s'\n",
476                         error_message(code), kt_name);
477                 retval = code;
478                 goto out;
479         }
480
481         while ((code = krb5_kt_next_entry(context, kt, &kte, &cursor)) == 0) {
482                 char *pname;
483                 if ((code = krb5_unparse_name(context, kte.principal,
484                                               &pname))) {
485                         printerr(0, "WARNING: Skipping keytab entry because "
486                                     "we failed to unparse principal name: %s\n",
487                                  error_message(code));
488                         krb5_kt_free_entry(context, &kte);
489                         continue;
490                 }
491                 printerr(2, "Processing keytab entry for principal '%s'\n",
492                          pname);
493 #ifdef HAVE_KRB5
494                 if ( (kte.principal->data[0].length == GSSD_SERVICE_NAME_LEN) &&
495                      (strncmp(kte.principal->data[0].data, GSSD_SERVICE_NAME,
496                               GSSD_SERVICE_NAME_LEN) == 0) &&
497 #else
498                 if ( (strlen(kte.principal->name.name_string.val[0]) == GSSD_SERVICE_NAME_LEN) &&
499                      (strncmp(kte.principal->name.name_string.val[0], GSSD_SERVICE_NAME,
500                               GSSD_SERVICE_NAME_LEN) == 0) &&
501                               
502 #endif
503                      (!gssd_have_realm_ple((void *)&kte.principal->realm)) ) {
504                         printerr(2, "We will use this entry (%s)\n", pname);
505                         ple = malloc(sizeof(struct gssd_k5_kt_princ));
506                         if (ple == NULL) {
507                                 printerr(0, "ERROR: could not allocate storage "
508                                             "for principal list entry\n");
509 #ifdef HAVE_KRB5
510                                 krb5_free_unparsed_name(context, pname);
511 #else
512                                 free(pname);
513 #endif
514                                 krb5_kt_free_entry(context, &kte);
515                                 retval = ENOMEM;
516                                 goto out;
517                         }
518                         /* These will be filled in later */
519                         ple->next = NULL;
520                         ple->ccname = NULL;
521                         ple->endtime = 0;
522                         if ((ple->realm =
523 #ifdef HAVE_KRB5
524                                 strndup(kte.principal->realm.data,
525                                         kte.principal->realm.length))
526 #else
527                                 strdup(kte.principal->realm))
528 #endif
529                                         == NULL) {
530                                 printerr(0, "ERROR: %s while copying realm to "
531                                             "principal list entry\n",
532                                          "not enough memory");
533 #ifdef HAVE_KRB5
534                                 krb5_free_unparsed_name(context, pname);
535 #else
536                                 free(pname);
537 #endif
538                                 krb5_kt_free_entry(context, &kte);
539                                 retval = ENOMEM;
540                                 goto out;
541                         }
542                         if ((code = krb5_copy_principal(context,
543                                         kte.principal, &ple->princ))) {
544                                 printerr(0, "ERROR: %s while copying principal "
545                                             "to principal list entry\n",
546                                         error_message(code));
547 #ifdef HAVE_KRB5
548                                 krb5_free_unparsed_name(context, pname);
549 #else
550                                 free(pname);
551 #endif
552                                 krb5_kt_free_entry(context, &kte);
553                                 retval = code;
554                                 goto out;
555                         }
556                         if (gssd_k5_kt_princ_list == NULL)
557                                 gssd_k5_kt_princ_list = ple;
558                         else {
559                                 ple->next = gssd_k5_kt_princ_list;
560                                 gssd_k5_kt_princ_list = ple;
561                         }
562                 }
563                 else {
564                         printerr(2, "We will NOT use this entry (%s)\n",
565                                 pname);
566                 }
567 #ifdef HAVE_KRB5
568                 krb5_free_unparsed_name(context, pname);
569 #else
570                 free(pname);
571 #endif
572                 krb5_kt_free_entry(context, &kte);
573         }
574
575         if ((code = krb5_kt_end_seq_get(context, kt, &cursor))) {
576                 printerr(0, "WARNING: %s while ending keytab scan for "
577                             "keytab '%s'\n",
578                          error_message(code), kt_name);
579         }
580
581         retval = 0;
582   out:
583         return retval;
584 }
585
586 /*
587  * Depending on the version of Kerberos, we either need to use
588  * a private function, or simply set the environment variable.
589  */
590 static void
591 gssd_set_krb5_ccache_name(char *ccname)
592 {
593 #ifdef USE_GSS_KRB5_CCACHE_NAME
594         u_int   maj_stat, min_stat;
595
596         printerr(2, "using gss_krb5_ccache_name to select krb5 ccache %s\n",
597                  ccname);
598         maj_stat = gss_krb5_ccache_name(&min_stat, ccname, NULL);
599         if (maj_stat != GSS_S_COMPLETE) {
600                 printerr(0, "WARNING: gss_krb5_ccache_name with "
601                         "name '%s' failed (%s)\n",
602                         ccname, error_message(min_stat));
603         }
604 #else
605         /*
606          * Set the KRB5CCNAME environment variable to tell the krb5 code
607          * which credentials cache to use.  (Instead of using the private
608          * function above for which there is no generic gssapi
609          * equivalent.)
610          */
611         printerr(2, "using environment variable to select krb5 ccache %s\n",
612                  ccname);
613         setenv("KRB5CCNAME", ccname, 1);
614 #endif
615 }
616
617 /*==========================*/
618 /*===  External routines ===*/
619 /*==========================*/
620
621 /*
622  * Attempt to find the best match for a credentials cache file
623  * given only a UID.  We really need more information, but we
624  * do the best we can.
625  *
626  * Returns:
627  *      void
628  */
629 void
630 gssd_setup_krb5_user_gss_ccache(uid_t uid, char *servername)
631 {
632         char                    buf[MAX_NETOBJ_SZ];
633         struct dirent           *d;
634
635         printerr(2, "getting credentials for client with uid %u for "
636                     "server %s\n", uid, servername);
637         memset(buf, 0, sizeof(buf));
638         if (gssd_find_existing_krb5_ccache(uid, &d)) {
639                 snprintf(buf, sizeof(buf), "FILE:%s/%s",
640                         ccachedir, d->d_name);
641                 free(d);
642         }
643         else
644                 snprintf(buf, sizeof(buf), "FILE:%s/%s%u",
645                         ccachedir, GSSD_DEFAULT_CRED_PREFIX, uid);
646         printerr(2, "using %s as credentials cache for client with "
647                     "uid %u for server %s\n", buf, uid, servername);
648         gssd_set_krb5_ccache_name(buf);
649 }
650
651 /*
652  * Let the gss code know where to find the machine credentials ccache.
653  *
654  * Returns:
655  *      void
656  */
657 void
658 gssd_setup_krb5_machine_gss_ccache(char *ccname)
659 {
660         printerr(2, "using %s as credentials cache for machine creds\n",
661                  ccname);
662         gssd_set_krb5_ccache_name(ccname);
663 }
664
665 /*
666  * The first time through this routine, go through the keytab and
667  * determine which keys we will try to use as machine credentials.
668  * Every time through this routine, try to obtain credentials using
669  * the keytab entries selected the first time through.
670  *
671  * Returns:
672  *      0 => obtained one or more credentials
673  *      nonzero => error
674  *
675  */
676
677 int
678 gssd_refresh_krb5_machine_creds(void)
679 {
680         krb5_context context = NULL;
681         krb5_keytab kt = NULL;;
682         krb5_error_code code;
683         int retval = -1;
684         struct gssd_k5_kt_princ *ple;
685         int gotone = 0;
686         static int processed_keytab = 0;
687
688
689         code = krb5_init_context(&context);
690         if (code) {
691                 printerr(0, "ERROR: %s while initializing krb5 in "
692                             "gssd_refresh_krb5_machine_creds\n",
693                          error_message(code));
694                 retval = code;
695                 goto out;
696         }
697
698         printerr(1, "Using keytab file '%s'\n", keytabfile);
699
700         if ((code = krb5_kt_resolve(context, keytabfile, &kt))) {
701                 printerr(0, "ERROR: %s while resolving keytab '%s'\n",
702                          error_message(code), keytabfile);
703                 goto out;
704         }
705
706         /* Only go through the keytab file once.  Only print messages once. */
707         if (gssd_k5_kt_princ_list == NULL && !processed_keytab) {
708                 processed_keytab = 1;
709                 gssd_process_krb5_keytab(context, kt, keytabfile);
710                 if (gssd_k5_kt_princ_list == NULL) {
711                         printerr(0, "ERROR: No usable keytab entries found in "
712                                     "keytab '%s'\n", keytabfile);
713                         printerr(0, "Do you have a valid keytab entry for "
714                                     "%s/<your.host>@<YOUR.REALM> in "
715                                     "keytab file %s ?\n",
716                                     GSSD_SERVICE_NAME, keytabfile);
717                         printerr(0, "Continuing without (machine) credentials "
718                                     "- nfs4 mounts with Kerberos will fail\n");
719                 }
720         }
721
722         /*
723          * If we don't have any keytab entries we liked, then we have a problem
724          */
725         if (gssd_k5_kt_princ_list == NULL) {
726                 retval = ENOENT;
727                 goto out;
728         }
729
730         /*
731          * Now go through the list of saved entries and get initial
732          * credentials for them (We can't do this while making the
733          * list because it messes up the keytab iteration cursor
734          * when we use the keytab to get credentials.)
735          */
736         for (ple = gssd_k5_kt_princ_list; ple; ple = ple->next) {
737                 if ((gssd_get_single_krb5_cred(context, kt, ple)) == 0) {
738                         gotone++;
739                 }
740         }
741         if (!gotone) {
742                 printerr(0, "ERROR: No usable machine credentials obtained\n");
743                 goto out;
744         }
745
746         retval = 0;
747   out:
748         if (kt) krb5_kt_close(context, kt);
749         krb5_free_context(context);
750
751         return retval;
752 }
753
754
755 /*
756  * Return an array of pointers to names of credential cache files
757  * which can be used to try to create gss contexts with a server.
758  *
759  * Returns:
760  *      0 => list is attached
761  *      nonzero => error
762  */
763 int
764 gssd_get_krb5_machine_cred_list(char ***list)
765 {
766         char **l;
767         int listinc = 10;
768         int listsize = listinc;
769         int i = 0;
770         int retval;
771         struct gssd_k5_kt_princ *ple;
772
773         /* Assume failure */
774         retval = -1;
775         *list = (char **) NULL;
776
777         /* Refresh machine credentials */
778         if ((retval = gssd_refresh_krb5_machine_creds())) {
779                 goto out;
780         }
781
782         if ((l = (char **) malloc(listsize * sizeof(char *))) == NULL) {
783                 retval = ENOMEM;
784                 goto out;
785         }
786
787         for (ple = gssd_k5_kt_princ_list; ple; ple = ple->next) {
788                 if (ple->ccname) {
789                         if (i + 1 > listsize) {
790                                 listsize += listinc;
791                                 l = (char **)
792                                         realloc(l, listsize * sizeof(char *));
793                                 if (l == NULL) {
794                                         retval = ENOMEM;
795                                         goto out;
796                                 }
797                         }
798                         if ((l[i++] = strdup(ple->ccname)) == NULL) {
799                                 retval = ENOMEM;
800                                 goto out;
801                         }
802                 }
803         }
804         if (i > 0) {
805                 l[i] = NULL;
806                 *list = l;
807                 retval = 0;
808                 goto out;
809         }
810   out:
811         return retval;
812 }
813
814 /*
815  * Frees the list of names returned in get_krb5_machine_cred_list()
816  */
817 void
818 gssd_free_krb5_machine_cred_list(char **list)
819 {
820         char **n;
821
822         if (list == NULL)
823                 return;
824         for (n = list; n && *n; n++) {
825                 free(*n);
826         }
827         free(list);
828 }
829
830 /*
831  * Called upon exit.  Destroys machine credentials.
832  */
833 void
834 gssd_destroy_krb5_machine_creds(void)
835 {
836         krb5_context context;
837         krb5_error_code code = 0;
838         krb5_ccache ccache;
839         struct gssd_k5_kt_princ *ple;
840
841         code = krb5_init_context(&context);
842         if (code) {
843                 printerr(0, "ERROR: %s while initializing krb5\n",
844                          error_message(code));
845                 goto out;
846         }
847
848         for (ple = gssd_k5_kt_princ_list; ple; ple = ple->next) {
849                 if (!ple->ccname)
850                         continue;
851                 if ((code = krb5_cc_resolve(context, ple->ccname, &ccache))) {
852                         printerr(0, "WARNING: %s while resolving credential "
853                                     "cache '%s' for destruction\n",
854                                  error_message(code), ple->ccname);
855                         continue;
856                 }
857
858                 if ((code = krb5_cc_destroy(context, ccache))) {
859                         printerr(0, "WARNING: %s while destroying credential "
860                                     "cache '%s'\n",
861                                  error_message(code), ple->ccname);
862                 }
863         }
864   out:
865         krb5_free_context(context);
866 }
867