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