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