]> git.decadent.org.uk Git - nfs-utils.git/blob - utils/gssd/krb5_util.c
2dcc2ee95e1c6f191945e1fc6703d17c50967c4c
[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(krb5_data *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         /* Don't consider anything but regular files. (No symlinks, etc.) */
150         if (d->d_type != DT_REG)
151                 return 0;
152
153         if (strstr(d->d_name, GSSD_DEFAULT_CRED_PREFIX))
154                 return 1;
155         else
156                 return 0;
157 }
158
159 /*
160  * Look in the GSSD_DEFAULT_CRED_DIR for files that look like they
161  * are Kerberos Credential Cache files for a given UID.  Return
162  * non-zero and the dirent pointer for the entry most likely to be
163  * what we want. Otherwise, return zero and no dirent pointer.
164  * The caller is responsible for freeing the dirent if one is returned.
165  *
166  * Returns:
167  *      0 => could not find an existing entry
168  *      1 => found an existing entry
169  */
170 static int
171 gssd_find_existing_krb5_ccache(uid_t uid, struct dirent **d)
172 {
173         struct dirent **namelist;
174         int n;
175         int i;
176         int found = 0;
177         struct dirent *best_match_dir = NULL;
178         struct stat best_match_stat, tmp_stat;
179
180         *d = NULL;
181         n = scandir(GSSD_DEFAULT_CRED_DIR, &namelist, select_krb5_ccache, 0);
182         if (n < 0) {
183                 perror("scandir looking for krb5 credentials caches");
184         }
185         else if (n > 0) {
186                 char substring[128];
187                 char statname[1024];
188                 snprintf(substring, sizeof(substring), "_%d", uid);
189                 for (i = 0; i < n; i++) {
190                         printerr(3, "CC file '%s' being considered\n",
191                                  namelist[i]->d_name);
192                         if (strstr(namelist[i]->d_name, substring)) {
193                                 snprintf(statname, sizeof(statname),
194                                          "%s/%s", GSSD_DEFAULT_CRED_DIR,
195                                          namelist[i]->d_name);
196                                 if (stat(statname, &tmp_stat)) {
197                                         printerr(0, "Error doing stat "
198                                                     "on file '%s'\n",
199                                                  statname);
200                                         continue;
201                                 }
202                                 printerr(3, "CC file '%s' matches "
203                                             "name check and has "
204                                             "mtime of %u\n",
205                                          namelist[i]->d_name,
206                                          tmp_stat.st_mtime);
207                                 /* if more than one match is found,
208                                  * return the most recent (the one
209                                  * with the latest mtime),
210                                  * and don't free the dirent */
211                                 if (!found) {
212                                         best_match_dir = namelist[i];
213                                         best_match_stat = tmp_stat;
214                                         found++;
215                                 }
216                                 else {
217                                         /*
218                                          * If the current match has
219                                          * an mtime later than the
220                                          * one we are looking at,
221                                          * then use the current match.
222                                          * Otherwise, we still have
223                                          * the best match.
224                                          */
225                                         if (tmp_stat.st_mtime >
226                                                     best_match_stat.st_mtime) {
227                                                 free(best_match_dir);
228                                                 best_match_dir = namelist[i];
229                                                 best_match_stat = tmp_stat;
230                                         }
231                                         else {
232                                                 free(namelist[i]);
233                                         }
234                                         printerr(3, "CC file '%s' is our "
235                                                     "current best match "
236                                                     "with mtime of %u\n",
237                                                  best_match_dir->d_name,
238                                                  best_match_stat.st_mtime);
239                                 }
240                         }
241                         else
242                                 free(namelist[i]);
243                 }
244                 free(namelist);
245         }
246         if (found)
247         {
248                 *d = best_match_dir;
249         }
250         return found;
251 }
252
253
254 #ifdef HAVE_SET_ALLOWABLE_ENCTYPES
255 /*
256  * this routine obtains a credentials handle via gss_acquire_cred()
257  * then calls gss_krb5_set_allowable_enctypes() to limit the encryption
258  * types negotiated.
259  *
260  * XXX Should call some function to determine the enctypes supported
261  * by the kernel. (Only need to do that once!)
262  *
263  * Returns:
264  *      0 => all went well
265  *     -1 => there was an error
266  */
267
268 int
269 limit_krb5_enctypes(struct rpc_gss_sec *sec, uid_t uid)
270 {
271         u_int maj_stat, min_stat;
272         gss_cred_id_t credh;
273 /*      krb5_enctype enctypes[] = {ENCTYPE_DES3_CBC_SHA1};
274                                    ENCTYPE_ARCFOUR_HMAC, */
275         krb5_enctype enctypes[] = {ENCTYPE_DES3_CBC_SHA1,
276                                    ENCTYPE_DES_CBC_MD5,
277                                    ENCTYPE_DES_CBC_CRC};
278         int num_enctypes = sizeof(enctypes) / sizeof(enctypes[0]);
279
280         maj_stat = gss_acquire_cred(&min_stat, NULL, 0,
281                                     GSS_C_NULL_OID_SET, GSS_C_INITIATE,
282                                     &credh, NULL, NULL);
283
284         if (maj_stat != GSS_S_COMPLETE) {
285                 printerr(0, "WARNING: error from gss_acquire_cred "
286                         "for user with uid %d (%s)\n",
287                         uid, error_message(min_stat));
288                 return -1;
289         }
290
291         maj_stat = gss_set_allowable_enctypes(&min_stat, credh, &krb5oid,
292                                              num_enctypes, &enctypes);
293         if (maj_stat != GSS_S_COMPLETE) {
294                 printerr(0, "WARNING: error from gss_set_allowable_enctypes "
295                         "for user with uid %d (%s)\n",
296                         uid, error_message(min_stat));
297                 return -1;
298         }
299         sec->cred = credh;
300
301         return 0;
302 }
303 #endif  /* HAVE_SET_ALLOWABLE_ENCTYPES */
304
305 /*
306  * Obtain credentials via a key in the keytab given
307  * a keytab handle and a gssd_k5_kt_princ structure.
308  * Checks to see if current credentials are expired,
309  * if not, uses the keytab to obtain new credentials.
310  *
311  * Returns:
312  *      0 => success (or credentials have not expired)
313  *      nonzero => error
314  */
315 static int
316 gssd_get_single_krb5_cred(krb5_context context,
317                           krb5_keytab kt,
318                           struct gssd_k5_kt_princ *ple)
319 {
320         krb5_get_init_creds_opt options;
321         krb5_creds my_creds;
322         krb5_ccache ccache = NULL;
323         char kt_name[BUFSIZ];
324         char cc_name[BUFSIZ];
325         int code;
326         time_t now = time(0);
327
328         memset(&my_creds, 0, sizeof(my_creds));
329
330         if (ple->ccname && ple->endtime > now) {
331                 printerr(2, "INFO: Credentials in CC '%s' are good until %d\n",
332                          ple->ccname, ple->endtime);
333                 code = 0;
334                 goto out;
335         }
336
337         if ((code = krb5_kt_get_name(context, kt, kt_name, BUFSIZ))) {
338                 printerr(0, "ERROR: Unable to get keytab name in "
339                             "gssd_get_single_krb5_cred\n");
340                 goto out;
341         }
342
343         krb5_get_init_creds_opt_init(&options);
344         krb5_get_init_creds_opt_set_address_list(&options, NULL);
345
346 #ifdef TEST_SHORT_LIFETIME
347         /* set a short lifetime (for debugging only!) */
348         printerr(0, "WARNING: Using (debug) short machine cred lifetime!\n");
349         krb5_get_init_creds_opt_set_tkt_life(&options, 5*60);
350 #endif
351         if ((code = krb5_get_init_creds_keytab(context, &my_creds, ple->princ,
352                                           kt, 0, 0, &options))) {
353                 char *pname;
354                 if ((krb5_unparse_name(context, ple->princ, &pname))) {
355                         pname = NULL;
356                 }
357                 printerr(0, "WARNING: %s while getting initial ticket for "
358                             "principal '%s' from keytab '%s'\n",
359                          error_message(code),
360                          pname ? pname : "<unparsable>", kt_name);
361                 if (pname) krb5_free_unparsed_name(context, pname);
362                 goto out;
363         }
364
365         /*
366          * Initialize cache file which we're going to be using
367          */
368
369         snprintf(cc_name, sizeof(cc_name), "FILE:%s/%s%s_%s",
370                 GSSD_DEFAULT_CRED_DIR, GSSD_DEFAULT_CRED_PREFIX,
371                 GSSD_DEFAULT_MACHINE_CRED_SUFFIX, ple->realm);
372         ple->endtime = my_creds.times.endtime;
373         ple->ccname = strdup(cc_name);
374         if (ple->ccname == NULL) {
375                 printerr(0, "ERROR: no storage to duplicate credentials "
376                             "cache name\n");
377                 code = ENOMEM;
378                 goto out;
379         }
380         if ((code = krb5_cc_resolve(context, cc_name, &ccache))) {
381                 printerr(0, "ERROR: %s while opening credential cache '%s'\n",
382                          error_message(code), cc_name);
383                 goto out;
384         }
385         if ((code = krb5_cc_initialize(context, ccache, ple->princ))) {
386                 printerr(0, "ERROR: %s while initializing credential "
387                          "cache '%s'\n", error_message(code), cc_name);
388                 goto out;
389         }
390         if ((code = krb5_cc_store_cred(context, ccache, &my_creds))) {
391                 printerr(0, "ERROR: %s while storing credentials in '%s'\n",
392                          error_message(code), cc_name);
393                 goto out;
394         }
395
396         code = 0;
397         printerr(1, "Using (machine) credentials cache: '%s'\n", cc_name);
398   out:
399         if (ccache)
400                 krb5_cc_close(context, ccache);
401         krb5_free_cred_contents(context, &my_creds);
402         return (code);
403 }
404
405 /*
406  * Determine if we already have a ple for the given realm
407  *
408  * Returns:
409  *      0 => no ple found for given realm
410  *      1 => found ple for given realm
411  */
412 static int
413 gssd_have_realm_ple(krb5_data *realm)
414 {
415         struct gssd_k5_kt_princ *ple;
416
417         for (ple = gssd_k5_kt_princ_list; ple; ple = ple->next) {
418                 if ((realm->length == strlen(ple->realm)) &&
419                     (strncmp(realm->data, ple->realm, realm->length) == 0)) {
420                     return 1;
421                 }
422         }
423         return 0;
424 }
425
426 /*
427  * Process the given keytab file and create a list of principals we
428  * might use to perform mount operations.
429  *
430  * Returns:
431  *      0 => Sucess
432  *      nonzero => Error
433  */
434 static int
435 gssd_process_krb5_keytab(krb5_context context, krb5_keytab kt, char *kt_name)
436 {
437         krb5_kt_cursor cursor;
438         krb5_keytab_entry kte;
439         krb5_error_code code;
440         struct gssd_k5_kt_princ *ple;
441         int retval = -1;
442
443         /*
444          * Look through each entry in the keytab file and determine
445          * if we might want to use it later to do a mount.  If so,
446          * save info in the global principal list
447          * (gssd_k5_kt_princ_list).
448          * Note: (ple == principal list entry)
449          */
450         if ((code = krb5_kt_start_seq_get(context, kt, &cursor))) {
451                 printerr(0, "ERROR: %s while beginning keytab scan "
452                             "for keytab '%s'\n",
453                         error_message(code), kt_name);
454                 retval = code;
455                 goto out;
456         }
457
458         while ((code = krb5_kt_next_entry(context, kt, &kte, &cursor)) == 0) {
459                 char *pname;
460                 if ((code = krb5_unparse_name(context, kte.principal,
461                                               &pname))) {
462                         printerr(0, "WARNING: Skipping keytab entry because "
463                                     "we failed to unparse principal name: %s\n",
464                                  error_message(code));
465                         continue;
466                 }
467                 printerr(2, "Processing keytab entry for principal '%s'\n",
468                          pname);
469                 if ( (kte.principal->data[0].length == GSSD_SERVICE_NAME_LEN) &&
470                      (strncmp(kte.principal->data[0].data, GSSD_SERVICE_NAME,
471                               GSSD_SERVICE_NAME_LEN) == 0) &&
472                      (!gssd_have_realm_ple(&kte.principal->realm)) ) {
473                         printerr(2, "We will use this entry (%s)\n", pname);
474                         ple = malloc(sizeof(struct gssd_k5_kt_princ));
475                         if (ple == NULL) {
476                                 printerr(0, "ERROR: could not allocate storage "
477                                             "for principal list entry\n");
478                                 krb5_free_unparsed_name(context, pname);
479                                 retval = ENOMEM;
480                                 goto out;
481                         }
482                         /* These will be filled in later */
483                         ple->next = NULL;
484                         ple->ccname = NULL;
485                         ple->endtime = 0;
486                         if ((ple->realm =
487                                 strndup(kte.principal->realm.data,
488                                         kte.principal->realm.length))
489                                         == NULL) {
490                                 printerr(0, "ERROR: %s while copying realm to "
491                                             "principal list entry\n",
492                                          "not enough memory");
493                                 krb5_free_unparsed_name(context, pname);
494                                 retval = ENOMEM;
495                                 goto out;
496                         }
497                         if ((code = krb5_copy_principal(context,
498                                         kte.principal, &ple->princ))) {
499                                 printerr(0, "ERROR: %s while copying principal "
500                                             "to principal list entry\n",
501                                         error_message(code));
502                                 krb5_free_unparsed_name(context, pname);
503                                 retval = code;
504                                 goto out;
505                         }
506                         if (gssd_k5_kt_princ_list == NULL)
507                                 gssd_k5_kt_princ_list = ple;
508                         else {
509                                 ple->next = gssd_k5_kt_princ_list;
510                                 gssd_k5_kt_princ_list = ple;
511                         }
512                 }
513                 else {
514                         printerr(2, "We will NOT use this entry (%s)\n",
515                                 pname);
516                 }
517                 krb5_free_unparsed_name(context, pname);
518         }
519
520         if ((code = krb5_kt_end_seq_get(context, kt, &cursor))) {
521                 printerr(0, "WARNING: %s while ending keytab scan for "
522                             "keytab '%s'\n",
523                          error_message(code), kt_name);
524         }
525
526         retval = 0;
527   out:
528         return retval;
529 }
530
531
532 /*==========================*/
533 /*===  External routines ===*/
534 /*==========================*/
535
536 /*
537  * Attempt to find the best match for a credentials cache file
538  * given only a UID.  We really need more information, but we
539  * do the best we can.
540  *
541  * Returns:
542  *      void
543  */
544 void
545 gssd_setup_krb5_user_gss_ccache(uid_t uid, char *servername)
546 {
547         char                    buf[MAX_NETOBJ_SZ];
548 #ifdef HAVE_GSS_KRB5_CCACHE_NAME
549         u_int                   min_stat;
550 #endif
551         struct dirent           *d;
552
553         printerr(2, "getting credentials for client with uid %u for "
554                     "server %s\n", uid, servername);
555         memset(buf, 0, sizeof(buf));
556         if (gssd_find_existing_krb5_ccache(uid, &d)) {
557                 snprintf(buf, sizeof(buf), "FILE:%s/%s",
558                         GSSD_DEFAULT_CRED_DIR, d->d_name);
559                 free(d);
560         }
561         else
562                 snprintf(buf, sizeof(buf), "FILE:%s/%s%u",
563                         GSSD_DEFAULT_CRED_DIR,
564                         GSSD_DEFAULT_CRED_PREFIX, uid);
565         printerr(2, "using %s as credentials cache for client with "
566                     "uid %u for server %s\n", buf, uid, servername);
567 #ifdef HAVE_GSS_KRB5_CCACHE_NAME
568         gss_krb5_ccache_name(&min_stat, buf, NULL);
569 #else
570         /*
571          * Set the KRB5CCNAME environment variable to tell the krb5 code
572          * which credentials cache to use.  (Instead of using the private
573          * function above for which there is no generic gssapi
574          * equivalent.)
575          */
576          setenv("KRB5CCNAME", buf, 1);
577 #endif
578 }
579
580 /*
581  * Let the gss code know where to find the machine credentials ccache.
582  *
583  * Returns:
584  *      void
585  */
586 void
587 gssd_setup_krb5_machine_gss_ccache(char *ccname)
588 {
589 #ifdef HAVE_GSS_KRB5_CCACHE_NAME
590         u_int                   min_stat;
591 #endif
592         printerr(2, "using %s as credentials cache for machine creds\n",
593                  ccname);
594 #ifdef HAVE_GSS_KRB5_CCACHE_NAME
595         gss_krb5_ccache_name(&min_stat, ccname, NULL);
596 #else
597         /*
598          * Set the KRB5CCNAME environment variable to tell the krb5 code
599          * which credentials cache to use.  (Instead of using the private
600          * function above for which there is no generic gssapi
601          * equivalent.)
602          */
603          setenv("KRB5CCNAME", ccname, 1);
604 #endif
605 }
606
607 /*
608  * The first time through this routine, go through the keytab and
609  * determine which keys we will try to use as machine credentials.
610  * Every time through this routine, try to obtain credentials using
611  * the keytab entries selected the first time through.
612  *
613  * Returns:
614  *      0 => obtained one or more credentials
615  *      nonzero => error
616  *
617  */
618
619 int
620 gssd_refresh_krb5_machine_creds(void)
621 {
622         krb5_context context = NULL;
623         krb5_keytab kt = NULL;;
624         krb5_error_code code;
625         int retval = -1;
626         struct gssd_k5_kt_princ *ple;
627         int gotone = 0;
628         static int processed_keytab = 0;
629
630
631         code = krb5_init_context(&context);
632         if (code) {
633                 printerr(0, "ERROR: %s while initializing krb5 in "
634                             "gssd_refresh_krb5_machine_creds\n",
635                          error_message(code));
636                 retval = code;
637                 goto out;
638         }
639
640         printerr(1, "Using keytab file '%s'\n", keytabfile);
641
642         if ((code = krb5_kt_resolve(context, keytabfile, &kt))) {
643                 printerr(0, "ERROR: %s while resolving keytab '%s'\n",
644                          error_message(code), keytabfile);
645                 goto out;
646         }
647
648         /* Only go through the keytab file once.  Only print messages once. */
649         if (gssd_k5_kt_princ_list == NULL && !processed_keytab) {
650                 processed_keytab = 1;
651                 gssd_process_krb5_keytab(context, kt, keytabfile);
652                 if (gssd_k5_kt_princ_list == NULL) {
653                         printerr(0, "ERROR: No usable keytab entries found in "
654                                     "keytab '%s'\n", keytabfile);
655                         printerr(0, "Do you have a valid keytab entry for "
656                                     "%s/<your.host>@<YOUR.REALM> in "
657                                     "keytab file %s ?\n",
658                                     GSSD_SERVICE_NAME, keytabfile);
659                         printerr(0, "Continuing without (machine) credentials "
660                                     "- nfs4 mounts with Kerberos will fail\n");
661                 }
662         }
663
664         /*
665          * If we don't have any keytab entries we liked, then we have a problem
666          */
667         if (gssd_k5_kt_princ_list == NULL) {
668                 retval = ENOENT;
669                 goto out;
670         }
671
672         /*
673          * Now go through the list of saved entries and get initial
674          * credentials for them (We can't do this while making the
675          * list because it messes up the keytab iteration cursor
676          * when we use the keytab to get credentials.)
677          */
678         for (ple = gssd_k5_kt_princ_list; ple; ple = ple->next) {
679                 if ((gssd_get_single_krb5_cred(context, kt, ple)) == 0) {
680                         gotone++;
681                 }
682         }
683         if (!gotone) {
684                 printerr(0, "ERROR: No usable machine credentials obtained\n");
685                 goto out;
686         }
687
688         retval = 0;
689   out:
690         if (kt) krb5_kt_close(context, kt);
691         krb5_free_context(context);
692
693         return retval;
694 }
695
696
697 /*
698  * Return an array of pointers to names of credential cache files
699  * which can be used to try to create gss contexts with a server.
700  *
701  * Returns:
702  *      0 => list is attached
703  *      nonzero => error
704  */
705 int
706 gssd_get_krb5_machine_cred_list(char ***list)
707 {
708         char **l;
709         int listinc = 10;
710         int listsize = listinc;
711         int i = 0;
712         int retval;
713         struct gssd_k5_kt_princ *ple;
714
715         /* Assume failure */
716         retval = -1;
717         *list = (char **) NULL;
718
719         /* Refresh machine credentials */
720         if ((retval = gssd_refresh_krb5_machine_creds())) {
721                 goto out;
722         }
723
724         if ((l = (char **) malloc(listsize * sizeof(char *))) == NULL) {
725                 retval = ENOMEM;
726                 goto out;
727         }
728
729         for (ple = gssd_k5_kt_princ_list; ple; ple = ple->next) {
730                 if (ple->ccname) {
731                         if (i + 1 > listsize) {
732                                 listsize += listinc;
733                                 l = (char **)
734                                         realloc(l, listsize * sizeof(char *));
735                                 if (l == NULL) {
736                                         retval = ENOMEM;
737                                         goto out;
738                                 }
739                         }
740                         if ((l[i++] = strdup(ple->ccname)) == NULL) {
741                                 retval = ENOMEM;
742                                 goto out;
743                         }
744                 }
745         }
746         if (i > 0) {
747                 l[i] = NULL;
748                 *list = l;
749                 retval = 0;
750                 goto out;
751         }
752   out:
753         return retval;
754 }
755
756 /*
757  * Frees the list of names returned in get_krb5_machine_cred_list()
758  */
759 void
760 gssd_free_krb5_machine_cred_list(char **list)
761 {
762         char **n;
763
764         if (list == NULL)
765                 return;
766         for (n = list; n && *n; n++) {
767                 free(*n);
768         }
769         free(list);
770 }
771
772 /*
773  * Called upon exit.  Destroys machine credentials.
774  */
775 void
776 gssd_destroy_krb5_machine_creds(void)
777 {
778         krb5_context context;
779         krb5_error_code code = 0;
780         krb5_ccache ccache;
781         struct gssd_k5_kt_princ *ple;
782
783         code = krb5_init_context(&context);
784         if (code) {
785                 printerr(0, "ERROR: %s while initializing krb5\n",
786                          error_message(code));
787                 goto out;
788         }
789
790         for (ple = gssd_k5_kt_princ_list; ple; ple = ple->next) {
791                 if (!ple->ccname)
792                         continue;
793                 if ((code = krb5_cc_resolve(context, ple->ccname, &ccache))) {
794                         printerr(0, "WARNING: %s while resolving credential "
795                                     "cache '%s' for destruction\n",
796                                  error_message(code), ple->ccname);
797                         continue;
798                 }
799
800                 if ((code = krb5_cc_destroy(context, ccache))) {
801                         printerr(0, "WARNING: %s while destroying credential "
802                                     "cache '%s'\n",
803                                  error_message(code), ple->ccname);
804                 }
805         }
806   out:
807         krb5_free_context(context);
808 }
809