]> git.decadent.org.uk Git - nfs-utils.git/blob - utils/gssd/krb5_util.c
8923b3bc56227d5f626e9ba6c238d629cef69630
[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 #ifdef HAVE_CONFIG_H
95 #include <config.h>
96 #endif  /* HAVE_CONFIG_H */
97
98 #ifndef _GNU_SOURCE
99 #define _GNU_SOURCE
100 #endif
101
102 #include <sys/param.h>
103 #include <rpc/rpc.h>
104 #include <sys/stat.h>
105 #include <sys/socket.h>
106 #include <arpa/inet.h>
107
108 #include <stdio.h>
109 #include <stdlib.h>
110 #include <unistd.h>
111 #include <string.h>
112 #include <dirent.h>
113 #include <netdb.h>
114 #include <ctype.h>
115 #include <errno.h>
116 #include <time.h>
117 #include <gssapi/gssapi.h>
118 #ifdef USE_PRIVATE_KRB5_FUNCTIONS
119 #include <gssapi/gssapi_krb5.h>
120 #endif
121 #include <krb5.h>
122 #include <rpc/auth_gss.h>
123
124 #include "gssd.h"
125 #include "err_util.h"
126 #include "gss_util.h"
127 #include "gss_oids.h"
128 #include "krb5_util.h"
129
130 /* Global list of principals/cache file names for machine credentials */
131 struct gssd_k5_kt_princ *gssd_k5_kt_princ_list = NULL;
132
133 /*==========================*/
134 /*===  Internal routines ===*/
135 /*==========================*/
136
137 static int select_krb5_ccache(const struct dirent *d);
138 static int gssd_find_existing_krb5_ccache(uid_t uid, char *dirname,
139                 struct dirent **d);
140 static int gssd_get_single_krb5_cred(krb5_context context,
141                 krb5_keytab kt, struct gssd_k5_kt_princ *ple);
142 static int query_krb5_ccache(const char* cred_cache, char **ret_princname,
143                 char **ret_realm);
144
145 /*
146  * Called from the scandir function to weed out potential krb5
147  * credentials cache files
148  *
149  * Returns:
150  *      0 => don't select this one
151  *      1 => select this one
152  */
153 static int
154 select_krb5_ccache(const struct dirent *d)
155 {
156         /*
157          * Note: We used to check d->d_type for DT_REG here,
158          * but apparenlty reiser4 always has DT_UNKNOWN.
159          * Check for IS_REG after stat() call instead.
160          */
161         if (strstr(d->d_name, GSSD_DEFAULT_CRED_PREFIX))
162                 return 1;
163         else
164                 return 0;
165 }
166
167 /*
168  * Look in directory "dirname" for files that look like they
169  * are Kerberos Credential Cache files for a given UID.  Return
170  * non-zero and the dirent pointer for the entry most likely to be
171  * what we want. Otherwise, return zero and no dirent pointer.
172  * The caller is responsible for freeing the dirent if one is returned.
173  *
174  * Returns:
175  *      0 => could not find an existing entry
176  *      1 => found an existing entry
177  */
178 static int
179 gssd_find_existing_krb5_ccache(uid_t uid, char *dirname, struct dirent **d)
180 {
181         struct dirent **namelist;
182         int n;
183         int i;
184         int found = 0;
185         struct dirent *best_match_dir = NULL;
186         struct stat best_match_stat, tmp_stat;
187         char buf[1030];
188         char *princname = NULL;
189         char *realm = NULL;
190         int score, best_match_score = 0;
191
192         memset(&best_match_stat, 0, sizeof(best_match_stat));
193         *d = NULL;
194         n = scandir(dirname, &namelist, select_krb5_ccache, 0);
195         if (n < 0) {
196                 printerr(1, "Error doing scandir on directory '%s': %s\n",
197                         dirname, strerror(errno));
198         }
199         else if (n > 0) {
200                 char statname[1024];
201                 for (i = 0; i < n; i++) {
202                         snprintf(statname, sizeof(statname),
203                                  "%s/%s", dirname, namelist[i]->d_name);
204                         printerr(3, "CC file '%s' being considered, "
205                                  "with preferred realm '%s'\n",
206                                  statname, preferred_realm ?
207                                         preferred_realm : "<none selected>");
208                         snprintf(buf, sizeof(buf), "FILE:%s/%s", dirname, 
209                                         namelist[i]->d_name);
210                         if (lstat(statname, &tmp_stat)) {
211                                 printerr(0, "Error doing stat on file '%s'\n",
212                                          statname);
213                                 free(namelist[i]);
214                                 continue;
215                         }
216                         /* Only pick caches owned by the user (uid) */
217                         if (tmp_stat.st_uid != uid) {
218                                 printerr(3, "CC file '%s' owned by %u, not %u\n",
219                                          statname, tmp_stat.st_uid, uid);
220                                 free(namelist[i]);
221                                 continue;
222                         }
223                         if (!S_ISREG(tmp_stat.st_mode)) {
224                                 printerr(3, "CC file '%s' is not a regular file\n",
225                                          statname);
226                                 free(namelist[i]);
227                                 continue;
228                         }
229                         if (!query_krb5_ccache(buf, &princname, &realm)) {
230                                 printerr(3, "CC file '%s' is expired or corrupt\n",
231                                          statname);
232                                 free(namelist[i]);
233                                 continue;
234                         }
235
236                         score = 0;
237                         if (preferred_realm &&
238                                         strcmp(realm, preferred_realm) == 0) 
239                                 score++;
240
241                         printerr(3, "CC file '%s'(%s@%s) passed all checks and"
242                                     " has mtime of %u\n",
243                                  statname, princname, realm, 
244                                  tmp_stat.st_mtime);
245                         /*
246                          * if more than one match is found, return the most
247                          * recent (the one with the latest mtime), and
248                          * don't free the dirent
249                          */
250                         if (!found) {
251                                 best_match_dir = namelist[i];
252                                 best_match_stat = tmp_stat;
253                                 best_match_score = score;
254                                 found++;
255                         }
256                         else {
257                                 /*
258                                  * If current score is higher than best match 
259                                  * score, we use the current match. Otherwise,
260                                  * if the current match has an mtime later
261                                  * than the one we are looking at, then use
262                                  * the current match.  Otherwise, we still
263                                  * have the best match.
264                                  */
265                                 if (best_match_score < score ||
266                                     (best_match_score == score && 
267                                        tmp_stat.st_mtime >
268                                             best_match_stat.st_mtime)) {
269                                         free(best_match_dir);
270                                         best_match_dir = namelist[i];
271                                         best_match_stat = tmp_stat;
272                                         best_match_score = score;
273                                 }
274                                 else {
275                                         free(namelist[i]);
276                                 }
277                                 printerr(3, "CC file '%s/%s' is our "
278                                             "current best match "
279                                             "with mtime of %u\n",
280                                          dirname, best_match_dir->d_name,
281                                          best_match_stat.st_mtime);
282                         }
283                         free(princname);
284                         free(realm);
285                 }
286                 free(namelist);
287         }
288         if (found)
289         {
290                 *d = best_match_dir;
291         }
292         return found;
293 }
294
295
296 #ifdef HAVE_SET_ALLOWABLE_ENCTYPES
297 /*
298  * this routine obtains a credentials handle via gss_acquire_cred()
299  * then calls gss_krb5_set_allowable_enctypes() to limit the encryption
300  * types negotiated.
301  *
302  * XXX Should call some function to determine the enctypes supported
303  * by the kernel. (Only need to do that once!)
304  *
305  * Returns:
306  *      0 => all went well
307  *     -1 => there was an error
308  */
309
310 int
311 limit_krb5_enctypes(struct rpc_gss_sec *sec, uid_t uid)
312 {
313         u_int maj_stat, min_stat;
314         gss_cred_id_t credh;
315         gss_OID_set_desc  desired_mechs;
316         krb5_enctype enctypes[] = { ENCTYPE_DES_CBC_CRC,
317                                     ENCTYPE_DES_CBC_MD5,
318                                     ENCTYPE_DES_CBC_MD4 };
319         int num_enctypes = sizeof(enctypes) / sizeof(enctypes[0]);
320
321         /* We only care about getting a krb5 cred */
322         desired_mechs.count = 1;
323         desired_mechs.elements = &krb5oid;
324
325         maj_stat = gss_acquire_cred(&min_stat, NULL, 0,
326                                     &desired_mechs, GSS_C_INITIATE,
327                                     &credh, NULL, NULL);
328
329         if (maj_stat != GSS_S_COMPLETE) {
330                 if (get_verbosity() > 0)
331                         pgsserr("gss_acquire_cred",
332                                 maj_stat, min_stat, &krb5oid);
333                 return -1;
334         }
335
336         maj_stat = gss_set_allowable_enctypes(&min_stat, credh, &krb5oid,
337                                              num_enctypes, &enctypes);
338         if (maj_stat != GSS_S_COMPLETE) {
339                 pgsserr("gss_set_allowable_enctypes",
340                         maj_stat, min_stat, &krb5oid);
341                 gss_release_cred(&min_stat, &credh);
342                 return -1;
343         }
344         sec->cred = credh;
345
346         return 0;
347 }
348 #endif  /* HAVE_SET_ALLOWABLE_ENCTYPES */
349
350 /*
351  * Obtain credentials via a key in the keytab given
352  * a keytab handle and a gssd_k5_kt_princ structure.
353  * Checks to see if current credentials are expired,
354  * if not, uses the keytab to obtain new credentials.
355  *
356  * Returns:
357  *      0 => success (or credentials have not expired)
358  *      nonzero => error
359  */
360 static int
361 gssd_get_single_krb5_cred(krb5_context context,
362                           krb5_keytab kt,
363                           struct gssd_k5_kt_princ *ple)
364 {
365 #if HAVE_KRB5_GET_INIT_CREDS_OPT_SET_ADDRESSLESS
366         krb5_get_init_creds_opt *init_opts = NULL;
367 #else
368         krb5_get_init_creds_opt options;
369 #endif
370         krb5_get_init_creds_opt *opts;
371         krb5_creds my_creds;
372         krb5_ccache ccache = NULL;
373         char kt_name[BUFSIZ];
374         char cc_name[BUFSIZ];
375         int code;
376         time_t now = time(0);
377         char *cache_type;
378         char *pname = NULL;
379
380         memset(&my_creds, 0, sizeof(my_creds));
381
382         if (ple->ccname && ple->endtime > now) {
383                 printerr(2, "INFO: Credentials in CC '%s' are good until %d\n",
384                          ple->ccname, ple->endtime);
385                 code = 0;
386                 goto out;
387         }
388
389         if ((code = krb5_kt_get_name(context, kt, kt_name, BUFSIZ))) {
390                 printerr(0, "ERROR: Unable to get keytab name in "
391                             "gssd_get_single_krb5_cred\n");
392                 goto out;
393         }
394
395         if ((krb5_unparse_name(context, ple->princ, &pname)))
396                 pname = NULL;
397
398 #if HAVE_KRB5_GET_INIT_CREDS_OPT_SET_ADDRESSLESS
399         code = krb5_get_init_creds_opt_alloc(context, &init_opts);
400         if (code) {
401                 printerr(0, "ERROR: %s allocating gic options\n",
402                          gssd_k5_err_msg(context, code));
403                 goto out;
404         }
405         if (krb5_get_init_creds_opt_set_addressless(context, init_opts, 1))
406                 printerr(1, "WARNING: Unable to set option for addressless "
407                          "tickets.  May have problems behind a NAT.\n");
408 #ifdef TEST_SHORT_LIFETIME
409         /* set a short lifetime (for debugging only!) */
410         printerr(0, "WARNING: Using (debug) short machine cred lifetime!\n");
411         krb5_get_init_creds_opt_set_tkt_life(init_opts, 5*60);
412 #endif
413         opts = init_opts;
414
415 #else   /* HAVE_KRB5_GET_INIT_CREDS_OPT_SET_ADDRESSLESS */
416
417         krb5_get_init_creds_opt_init(&options);
418         krb5_get_init_creds_opt_set_address_list(&options, NULL);
419 #ifdef TEST_SHORT_LIFETIME
420         /* set a short lifetime (for debugging only!) */
421         printerr(0, "WARNING: Using (debug) short machine cred lifetime!\n");
422         krb5_get_init_creds_opt_set_tkt_life(&options, 5*60);
423 #endif
424         opts = &options;
425 #endif
426
427         if ((code = krb5_get_init_creds_keytab(context, &my_creds, ple->princ,
428                                                kt, 0, NULL, opts))) {
429                 printerr(1, "WARNING: %s while getting initial ticket for "
430                          "principal '%s' using keytab '%s'\n",
431                          gssd_k5_err_msg(context, code),
432                          pname ? pname : "<unparsable>", kt_name);
433                 goto out;
434         }
435
436         /*
437          * Initialize cache file which we're going to be using
438          */
439
440         if (use_memcache)
441             cache_type = "MEMORY";
442         else
443             cache_type = "FILE";
444         snprintf(cc_name, sizeof(cc_name), "%s:%s/%s%s_%s",
445                 cache_type,
446                 ccachesearch[0], GSSD_DEFAULT_CRED_PREFIX,
447                 GSSD_DEFAULT_MACHINE_CRED_SUFFIX, ple->realm);
448         ple->endtime = my_creds.times.endtime;
449         if (ple->ccname != NULL)
450                 free(ple->ccname);
451         ple->ccname = strdup(cc_name);
452         if (ple->ccname == NULL) {
453                 printerr(0, "ERROR: no storage to duplicate credentials "
454                             "cache name '%s'\n", cc_name);
455                 code = ENOMEM;
456                 goto out;
457         }
458         if ((code = krb5_cc_resolve(context, cc_name, &ccache))) {
459                 printerr(0, "ERROR: %s while opening credential cache '%s'\n",
460                          gssd_k5_err_msg(context, code), cc_name);
461                 goto out;
462         }
463         if ((code = krb5_cc_initialize(context, ccache, ple->princ))) {
464                 printerr(0, "ERROR: %s while initializing credential "
465                          "cache '%s'\n", gssd_k5_err_msg(context, code),
466                          cc_name);
467                 goto out;
468         }
469         if ((code = krb5_cc_store_cred(context, ccache, &my_creds))) {
470                 printerr(0, "ERROR: %s while storing credentials in '%s'\n",
471                          gssd_k5_err_msg(context, code), cc_name);
472                 goto out;
473         }
474
475         code = 0;
476         printerr(2, "Successfully obtained machine credentials for "
477                  "principal '%s' stored in ccache '%s'\n", pname, cc_name);
478   out:
479 #if HAVE_KRB5_GET_INIT_CREDS_OPT_SET_ADDRESSLESS
480         if (init_opts)
481                 krb5_get_init_creds_opt_free(context, init_opts);
482 #endif
483         if (pname)
484                 k5_free_unparsed_name(context, pname);
485         if (ccache)
486                 krb5_cc_close(context, ccache);
487         krb5_free_cred_contents(context, &my_creds);
488         return (code);
489 }
490
491 /*
492  * Depending on the version of Kerberos, we either need to use
493  * a private function, or simply set the environment variable.
494  */
495 static void
496 gssd_set_krb5_ccache_name(char *ccname)
497 {
498 #ifdef USE_GSS_KRB5_CCACHE_NAME
499         u_int   maj_stat, min_stat;
500
501         printerr(2, "using gss_krb5_ccache_name to select krb5 ccache %s\n",
502                  ccname);
503         maj_stat = gss_krb5_ccache_name(&min_stat, ccname, NULL);
504         if (maj_stat != GSS_S_COMPLETE) {
505                 printerr(0, "WARNING: gss_krb5_ccache_name with "
506                         "name '%s' failed (%s)\n",
507                         ccname, error_message(min_stat));
508         }
509 #else
510         /*
511          * Set the KRB5CCNAME environment variable to tell the krb5 code
512          * which credentials cache to use.  (Instead of using the private
513          * function above for which there is no generic gssapi
514          * equivalent.)
515          */
516         printerr(2, "using environment variable to select krb5 ccache %s\n",
517                  ccname);
518         setenv("KRB5CCNAME", ccname, 1);
519 #endif
520 }
521
522 /*
523  * Given a principal, find a matching ple structure
524  */
525 static struct gssd_k5_kt_princ *
526 find_ple_by_princ(krb5_context context, krb5_principal princ)
527 {
528         struct gssd_k5_kt_princ *ple;
529
530         for (ple = gssd_k5_kt_princ_list; ple != NULL; ple = ple->next) {
531                 if (krb5_principal_compare(context, ple->princ, princ))
532                         return ple;
533         }
534         /* no match found */
535         return NULL;
536 }
537
538 /*
539  * Create, initialize, and add a new ple structure to the global list
540  */
541 static struct gssd_k5_kt_princ *
542 new_ple(krb5_context context, krb5_principal princ)
543 {
544         struct gssd_k5_kt_princ *ple = NULL, *p;
545         krb5_error_code code;
546         char *default_realm;
547         int is_default_realm = 0;
548
549         ple = malloc(sizeof(struct gssd_k5_kt_princ));
550         if (ple == NULL)
551                 goto outerr;
552         memset(ple, 0, sizeof(*ple));
553
554 #ifdef HAVE_KRB5
555         ple->realm = strndup(princ->realm.data,
556                              princ->realm.length);
557 #else
558         ple->realm = strdup(princ->realm);
559 #endif
560         if (ple->realm == NULL)
561                 goto outerr;
562         code = krb5_copy_principal(context, princ, &ple->princ);
563         if (code)
564                 goto outerr;
565
566         /*
567          * Add new entry onto the list (if this is the default
568          * realm, always add to the front of the list)
569          */
570
571         code = krb5_get_default_realm(context, &default_realm);
572         if (code == 0) {
573                 if (strcmp(ple->realm, default_realm) == 0)
574                         is_default_realm = 1;
575                 k5_free_default_realm(context, default_realm);
576         }
577
578         if (is_default_realm) {
579                 ple->next = gssd_k5_kt_princ_list;
580                 gssd_k5_kt_princ_list = ple;
581         } else {
582                 p = gssd_k5_kt_princ_list;
583                 while (p != NULL && p->next != NULL)
584                         p = p->next;
585                 if (p == NULL)
586                         gssd_k5_kt_princ_list = ple;
587                 else
588                         p->next = ple;
589         }
590
591         return ple;
592 outerr:
593         if (ple) {
594                 if (ple->realm)
595                         free(ple->realm);
596                 free(ple);
597         }
598         return NULL;
599 }
600
601 /*
602  * Given a principal, find an existing ple structure, or create one
603  */
604 static struct gssd_k5_kt_princ *
605 get_ple_by_princ(krb5_context context, krb5_principal princ)
606 {
607         struct gssd_k5_kt_princ *ple;
608
609         /* Need to serialize list if we ever become multi-threaded! */
610
611         ple = find_ple_by_princ(context, princ);
612         if (ple == NULL) {
613                 ple = new_ple(context, princ);
614         }
615
616         return ple;
617 }
618
619 /*
620  * Given a (possibly unqualified) hostname,
621  * return the fully qualified (lower-case!) hostname
622  */
623 static int
624 get_full_hostname(const char *inhost, char *outhost, int outhostlen)
625 {
626         struct addrinfo *addrs = NULL;
627         struct addrinfo hints;
628         int retval;
629         char *c;
630
631         memset(&hints, 0, sizeof(hints));
632         hints.ai_socktype = SOCK_STREAM;
633         hints.ai_family = PF_UNSPEC;
634         hints.ai_flags = AI_CANONNAME;
635
636         /* Get full target hostname */
637         retval = getaddrinfo(inhost, NULL, &hints, &addrs);
638         if (retval) {
639                 printerr(1, "%s while getting full hostname for '%s'\n",
640                          gai_strerror(retval), inhost);
641                 goto out;
642         }
643         strncpy(outhost, addrs->ai_canonname, outhostlen);
644         freeaddrinfo(addrs);
645         for (c = outhost; *c != '\0'; c++)
646             *c = tolower(*c);
647
648         printerr(3, "Full hostname for '%s' is '%s'\n", inhost, outhost);
649         retval = 0;
650 out:
651         return retval;
652 }
653
654 /* 
655  * If principal matches the given realm and service name,
656  * and has *any* instance (hostname), return 1.
657  * Otherwise return 0, indicating no match.
658  */
659 static int
660 realm_and_service_match(krb5_context context, krb5_principal p,
661                         const char *realm, const char *service)
662 {
663 #ifdef HAVE_KRB5
664         /* Must have two components */
665         if (p->length != 2)
666                 return 0;
667         if ((strlen(realm) == p->realm.length)
668             && (strncmp(realm, p->realm.data, p->realm.length) == 0)
669             && (strlen(service) == p->data[0].length)
670             && (strncmp(service, p->data[0].data, p->data[0].length) == 0))
671                 return 1;
672 #else
673         const char *name, *inst;
674
675         if (p->name.name_string.len != 2)
676                 return 0;
677         name = krb5_principal_get_comp_string(context, p, 0);
678         inst = krb5_principal_get_comp_string(context, p, 1);
679         if (name == NULL || inst == NULL)
680                 return 0;
681         if ((strcmp(realm, p->realm) == 0)
682             && (strcmp(service, name) == 0))
683                 return 1;
684 #endif
685         return 0;
686 }
687
688 /*
689  * Search the given keytab file looking for an entry with the given
690  * service name and realm, ignoring hostname (instance).
691  *
692  * Returns:
693  *      0 => No error
694  *      non-zero => An error occurred
695  *
696  * If a keytab entry is found, "found" is set to one, and the keytab
697  * entry is returned in "kte".  Otherwise, "found" is zero, and the
698  * value of "kte" is unpredictable.
699  */
700 static int
701 gssd_search_krb5_keytab(krb5_context context, krb5_keytab kt,
702                         const char *realm, const char *service,
703                         int *found, krb5_keytab_entry *kte)
704 {
705         krb5_kt_cursor cursor;
706         krb5_error_code code;
707         struct gssd_k5_kt_princ *ple;
708         int retval = -1;
709         char kt_name[BUFSIZ];
710         char *pname;
711
712         if (found == NULL) {
713                 retval = EINVAL;
714                 goto out;
715         }
716         *found = 0;
717
718         /*
719          * Look through each entry in the keytab file and determine
720          * if we might want to use it as machine credentials.  If so,
721          * save info in the global principal list (gssd_k5_kt_princ_list).
722          */
723         if ((code = krb5_kt_get_name(context, kt, kt_name, BUFSIZ))) {
724                 printerr(0, "ERROR: %s attempting to get keytab name\n",
725                          gssd_k5_err_msg(context, code));
726                 retval = code;
727                 goto out;
728         }
729         if ((code = krb5_kt_start_seq_get(context, kt, &cursor))) {
730                 printerr(0, "ERROR: %s while beginning keytab scan "
731                             "for keytab '%s'\n",
732                         gssd_k5_err_msg(context, code), kt_name);
733                 retval = code;
734                 goto out;
735         }
736
737         while ((code = krb5_kt_next_entry(context, kt, kte, &cursor)) == 0) {
738                 if ((code = krb5_unparse_name(context, kte->principal,
739                                               &pname))) {
740                         printerr(0, "WARNING: Skipping keytab entry because "
741                                  "we failed to unparse principal name: %s\n",
742                                  gssd_k5_err_msg(context, code));
743                         k5_free_kt_entry(context, kte);
744                         continue;
745                 }
746                 printerr(4, "Processing keytab entry for principal '%s'\n",
747                          pname);
748                 /* Use the first matching keytab entry found */
749                 if ((realm_and_service_match(context, kte->principal, realm,
750                                              service))) {
751                         printerr(4, "We WILL use this entry (%s)\n", pname);
752                         ple = get_ple_by_princ(context, kte->principal);
753                         /*
754                          * Return, don't free, keytab entry if
755                          * we were successful!
756                          */
757                         if (ple == NULL) {
758                                 retval = ENOMEM;
759                                 k5_free_kt_entry(context, kte);
760                         } else {
761                                 retval = 0;
762                                 *found = 1;
763                         }
764                         k5_free_unparsed_name(context, pname);
765                         break;
766                 }
767                 else {
768                         printerr(4, "We will NOT use this entry (%s)\n",
769                                 pname);
770                 }
771                 k5_free_unparsed_name(context, pname);
772                 k5_free_kt_entry(context, kte);
773         }
774
775         if ((code = krb5_kt_end_seq_get(context, kt, &cursor))) {
776                 printerr(0, "WARNING: %s while ending keytab scan for "
777                             "keytab '%s'\n",
778                          gssd_k5_err_msg(context, code), kt_name);
779         }
780
781         retval = 0;
782   out:
783         return retval;
784 }
785
786 /*
787  * Find a keytab entry to use for a given target hostname.
788  * Tries to find the most appropriate keytab to use given the
789  * name of the host we are trying to connect with.
790  */
791 static int
792 find_keytab_entry(krb5_context context, krb5_keytab kt, const char *hostname,
793                   krb5_keytab_entry *kte)
794 {
795         krb5_error_code code;
796         const char *svcnames[] = { "root", "nfs", "host", NULL };
797         char **realmnames = NULL;
798         char myhostname[NI_MAXHOST], targethostname[NI_MAXHOST];
799         int i, j, retval;
800         char *default_realm = NULL;
801         char *realm;
802         int tried_all = 0, tried_default = 0;
803         krb5_principal princ;
804
805
806         /* Get full target hostname */
807         retval = get_full_hostname(hostname, targethostname,
808                                    sizeof(targethostname));
809         if (retval)
810                 goto out;
811
812         /* Get full local hostname */
813         retval = gethostname(myhostname, sizeof(myhostname));
814         if (retval) {
815                 printerr(1, "%s while getting local hostname\n",
816                          gssd_k5_err_msg(context, retval));
817                 goto out;
818         }
819         retval = get_full_hostname(myhostname, myhostname, sizeof(myhostname));
820         if (retval)
821                 goto out;
822
823         code = krb5_get_default_realm(context, &default_realm);
824         if (code) {
825                 retval = code;
826                 printerr(1, "%s while getting default realm name\n",
827                          gssd_k5_err_msg(context, code));
828                 goto out;
829         }
830
831         /*
832          * Get the realm name(s) for the target hostname.
833          * In reality, this function currently only returns a
834          * single realm, but we code with the assumption that
835          * someday it may actually return a list.
836          */
837         code = krb5_get_host_realm(context, targethostname, &realmnames);
838         if (code) {
839                 printerr(0, "ERROR: %s while getting realm(s) for host '%s'\n",
840                          gssd_k5_err_msg(context, code), targethostname);
841                 retval = code;
842                 goto out;
843         }
844
845         /*
846          * Try the "appropriate" realm first, and if nothing found for that
847          * realm, try the default realm (if it hasn't already been tried).
848          */
849         i = 0;
850         realm = realmnames[i];
851         while (1) {
852                 if (realm == NULL) {
853                         tried_all = 1;
854                         if (!tried_default)
855                                 realm = default_realm;
856                 }
857                 if (tried_all && tried_default)
858                         break;
859                 if (strcmp(realm, default_realm) == 0)
860                         tried_default = 1;
861                 for (j = 0; svcnames[j] != NULL; j++) {
862                         code = krb5_build_principal_ext(context, &princ,
863                                                         strlen(realm),
864                                                         realm,
865                                                         strlen(svcnames[j]),
866                                                         svcnames[j],
867                                                         strlen(myhostname),
868                                                         myhostname,
869                                                         NULL);
870                         if (code) {
871                                 printerr(1, "%s while building principal for "
872                                          "'%s/%s@%s'\n",
873                                          gssd_k5_err_msg(context, code),
874                                          svcnames[j], myhostname, realm);
875                                 continue;
876                         }
877                         code = krb5_kt_get_entry(context, kt, princ, 0, 0, kte);
878                         krb5_free_principal(context, princ);
879                         if (code) {
880                                 printerr(3, "%s while getting keytab entry for "
881                                          "'%s/%s@%s'\n",
882                                          gssd_k5_err_msg(context, code),
883                                          svcnames[j], myhostname, realm);
884                         } else {
885                                 printerr(3, "Success getting keytab entry for "
886                                          "'%s/%s@%s'\n",
887                                          svcnames[j], myhostname, realm);
888                                 retval = 0;
889                                 goto out;
890                         }
891                         retval = code;
892                 }
893                 /*
894                  * Nothing found with our hostname instance, now look for
895                  * names with any instance (they must have an instance)
896                  */
897                 for (j = 0; svcnames[j] != NULL; j++) {
898                         int found = 0;
899                         code = gssd_search_krb5_keytab(context, kt, realm,
900                                                        svcnames[j], &found, kte);
901                         if (!code && found) {
902                                 printerr(3, "Success getting keytab entry for "
903                                          "%s/*@%s\n", svcnames[j], realm);
904                                 retval = 0;
905                                 goto out;
906                         }
907                 }
908                 if (!tried_all) {
909                         i++;
910                         realm = realmnames[i];
911                 }
912         }
913 out:
914         if (default_realm)
915                 k5_free_default_realm(context, default_realm);
916         if (realmnames)
917                 krb5_free_host_realm(context, realmnames);
918         return retval;
919 }
920
921
922 static inline int data_is_equal(krb5_data d1, krb5_data d2)
923 {
924         return (d1.length == d2.length
925                 && memcmp(d1.data, d2.data, d1.length) == 0);
926 }
927
928 static int
929 check_for_tgt(krb5_context context, krb5_ccache ccache,
930               krb5_principal principal)
931 {
932         krb5_error_code ret;
933         krb5_creds creds;
934         krb5_cc_cursor cur;
935         int found = 0;
936
937         ret = krb5_cc_start_seq_get(context, ccache, &cur);
938         if (ret) 
939                 return 0;
940
941         while (!found &&
942                 (ret = krb5_cc_next_cred(context, ccache, &cur, &creds)) == 0) {
943                 if (creds.server->length == 2 &&
944                                 data_is_equal(creds.server->realm,
945                                               principal->realm) &&
946                                 creds.server->data[0].length == 6 &&
947                                 memcmp(creds.server->data[0].data,
948                                                 "krbtgt", 6) == 0 &&
949                                 data_is_equal(creds.server->data[1],
950                                               principal->realm) &&
951                                 creds.times.endtime > time(NULL))
952                         found = 1;
953                 krb5_free_cred_contents(context, &creds);
954         }
955         krb5_cc_end_seq_get(context, ccache, &cur);
956
957         return found;
958 }
959
960 static int
961 query_krb5_ccache(const char* cred_cache, char **ret_princname,
962                   char **ret_realm)
963 {
964         krb5_error_code ret;
965         krb5_context context;
966         krb5_ccache ccache;
967         krb5_principal principal;
968         int found = 0;
969         char *str = NULL;
970         char *princstring;
971
972         ret = krb5_init_context(&context);
973         if (ret) 
974                 return 0;
975
976         if(!cred_cache || krb5_cc_resolve(context, cred_cache, &ccache))
977                 goto err_cache;
978
979         if (krb5_cc_set_flags(context, ccache, 0))
980                 goto err_princ;
981
982         ret = krb5_cc_get_principal(context, ccache, &principal);
983         if (ret) 
984                 goto err_princ;
985
986         found = check_for_tgt(context, ccache, principal);
987         if (found) {
988                 ret = krb5_unparse_name(context, principal, &princstring);
989                 if (ret == 0) {
990                     if ((str = strchr(princstring, '@')) != NULL) {
991                             *str = '\0';
992                             *ret_princname = strdup(princstring);
993                             *ret_realm = strdup(str+1);
994                     }
995                     k5_free_unparsed_name(context, princstring);
996                 } else {
997                         found = 0;
998                 }
999         }
1000         krb5_free_principal(context, principal);
1001 err_princ:
1002         krb5_cc_set_flags(context, ccache,  KRB5_TC_OPENCLOSE);
1003         krb5_cc_close(context, ccache);
1004 err_cache:
1005         krb5_free_context(context);
1006         return found;
1007 }
1008
1009 /*==========================*/
1010 /*===  External routines ===*/
1011 /*==========================*/
1012
1013 /*
1014  * Attempt to find the best match for a credentials cache file
1015  * given only a UID.  We really need more information, but we
1016  * do the best we can.
1017  *
1018  * Returns:
1019  *      0 => a ccache was found
1020  *      1 => no ccache was found
1021  */
1022 int
1023 gssd_setup_krb5_user_gss_ccache(uid_t uid, char *servername, char *dirname)
1024 {
1025         char                    buf[MAX_NETOBJ_SZ];
1026         struct dirent           *d;
1027
1028         printerr(2, "getting credentials for client with uid %u for "
1029                     "server %s\n", uid, servername);
1030         memset(buf, 0, sizeof(buf));
1031         if (gssd_find_existing_krb5_ccache(uid, dirname, &d)) {
1032                 snprintf(buf, sizeof(buf), "FILE:%s/%s", dirname, d->d_name);
1033                 free(d);
1034         }
1035         else
1036                 return 1;
1037         printerr(2, "using %s as credentials cache for client with "
1038                     "uid %u for server %s\n", buf, uid, servername);
1039         gssd_set_krb5_ccache_name(buf);
1040         return 0;
1041 }
1042
1043 /*
1044  * Let the gss code know where to find the machine credentials ccache.
1045  *
1046  * Returns:
1047  *      void
1048  */
1049 void
1050 gssd_setup_krb5_machine_gss_ccache(char *ccname)
1051 {
1052         printerr(2, "using %s as credentials cache for machine creds\n",
1053                  ccname);
1054         gssd_set_krb5_ccache_name(ccname);
1055 }
1056
1057 /*
1058  * Return an array of pointers to names of credential cache files
1059  * which can be used to try to create gss contexts with a server.
1060  *
1061  * Returns:
1062  *      0 => list is attached
1063  *      nonzero => error
1064  */
1065 int
1066 gssd_get_krb5_machine_cred_list(char ***list)
1067 {
1068         char **l;
1069         int listinc = 10;
1070         int listsize = listinc;
1071         int i = 0;
1072         int retval;
1073         struct gssd_k5_kt_princ *ple;
1074
1075         /* Assume failure */
1076         retval = -1;
1077         *list = (char **) NULL;
1078
1079         if ((l = (char **) malloc(listsize * sizeof(char *))) == NULL) {
1080                 retval = ENOMEM;
1081                 goto out;
1082         }
1083
1084         /* Need to serialize list if we ever become multi-threaded! */
1085
1086         for (ple = gssd_k5_kt_princ_list; ple; ple = ple->next) {
1087                 if (ple->ccname) {
1088                         /* Make sure cred is up-to-date before returning it */
1089                         retval = gssd_refresh_krb5_machine_credential(NULL, ple);
1090                         if (retval)
1091                                 continue;
1092                         if (i + 1 > listsize) {
1093                                 listsize += listinc;
1094                                 l = (char **)
1095                                         realloc(l, listsize * sizeof(char *));
1096                                 if (l == NULL) {
1097                                         retval = ENOMEM;
1098                                         goto out;
1099                                 }
1100                         }
1101                         if ((l[i++] = strdup(ple->ccname)) == NULL) {
1102                                 retval = ENOMEM;
1103                                 goto out;
1104                         }
1105                 }
1106         }
1107         if (i > 0) {
1108                 l[i] = NULL;
1109                 *list = l;
1110                 retval = 0;
1111                 goto out;
1112         }
1113   out:
1114         return retval;
1115 }
1116
1117 /*
1118  * Frees the list of names returned in get_krb5_machine_cred_list()
1119  */
1120 void
1121 gssd_free_krb5_machine_cred_list(char **list)
1122 {
1123         char **n;
1124
1125         if (list == NULL)
1126                 return;
1127         for (n = list; n && *n; n++) {
1128                 free(*n);
1129         }
1130         free(list);
1131 }
1132
1133 /*
1134  * Called upon exit.  Destroys machine credentials.
1135  */
1136 void
1137 gssd_destroy_krb5_machine_creds(void)
1138 {
1139         krb5_context context;
1140         krb5_error_code code = 0;
1141         krb5_ccache ccache;
1142         struct gssd_k5_kt_princ *ple;
1143
1144         code = krb5_init_context(&context);
1145         if (code) {
1146                 printerr(0, "ERROR: %s while initializing krb5\n",
1147                          gssd_k5_err_msg(NULL, code));
1148                 goto out;
1149         }
1150
1151         for (ple = gssd_k5_kt_princ_list; ple; ple = ple->next) {
1152                 if (!ple->ccname)
1153                         continue;
1154                 if ((code = krb5_cc_resolve(context, ple->ccname, &ccache))) {
1155                         printerr(0, "WARNING: %s while resolving credential "
1156                                     "cache '%s' for destruction\n",
1157                                  gssd_k5_err_msg(context, code), ple->ccname);
1158                         continue;
1159                 }
1160
1161                 if ((code = krb5_cc_destroy(context, ccache))) {
1162                         printerr(0, "WARNING: %s while destroying credential "
1163                                     "cache '%s'\n",
1164                                  gssd_k5_err_msg(context, code), ple->ccname);
1165                 }
1166         }
1167   out:
1168         krb5_free_context(context);
1169 }
1170
1171 /*
1172  * Obtain (or refresh if necessary) Kerberos machine credentials
1173  */
1174 int
1175 gssd_refresh_krb5_machine_credential(char *hostname,
1176                                      struct gssd_k5_kt_princ *ple)
1177 {
1178         krb5_error_code code = 0;
1179         krb5_context context;
1180         krb5_keytab kt = NULL;;
1181         int retval = 0;
1182
1183         if (hostname == NULL && ple == NULL)
1184                 return EINVAL;
1185
1186         code = krb5_init_context(&context);
1187         if (code) {
1188                 printerr(0, "ERROR: %s: %s while initializing krb5 context\n",
1189                          __FUNCTION__, gssd_k5_err_msg(NULL, code));
1190                 retval = code;
1191                 goto out;
1192         }
1193
1194         if ((code = krb5_kt_resolve(context, keytabfile, &kt))) {
1195                 printerr(0, "ERROR: %s: %s while resolving keytab '%s'\n",
1196                          __FUNCTION__, gssd_k5_err_msg(context, code),
1197                          keytabfile);
1198                 goto out;
1199         }
1200
1201         if (ple == NULL) {
1202                 krb5_keytab_entry kte;
1203
1204                 code = find_keytab_entry(context, kt, hostname, &kte);
1205                 if (code) {
1206                         printerr(0, "ERROR: %s: no usable keytab entry found "
1207                                  "in keytab %s for connection with host %s\n",
1208                                  __FUNCTION__, keytabfile, hostname);
1209                         retval = code;
1210                         goto out;
1211                 }
1212
1213                 ple = get_ple_by_princ(context, kte.principal);
1214                 k5_free_kt_entry(context, &kte);
1215                 if (ple == NULL) {
1216                         char *pname;
1217                         if ((krb5_unparse_name(context, kte.principal, &pname))) {
1218                                 pname = NULL;
1219                         }
1220                         printerr(0, "ERROR: %s: Could not locate or create "
1221                                  "ple struct for principal %s for connection "
1222                                  "with host %s\n",
1223                                  __FUNCTION__, pname ? pname : "<unparsable>",
1224                                  hostname);
1225                         if (pname) k5_free_unparsed_name(context, pname);
1226                         goto out;
1227                 }
1228         }
1229         retval = gssd_get_single_krb5_cred(context, kt, ple);
1230 out:
1231         if (kt)
1232                 krb5_kt_close(context, kt);
1233         krb5_free_context(context);
1234         return retval;
1235 }
1236
1237 /*
1238  * A common routine for getting the Kerberos error message
1239  */
1240 const char *
1241 gssd_k5_err_msg(krb5_context context, krb5_error_code code)
1242 {
1243         const char *msg = NULL;
1244 #if HAVE_KRB5_GET_ERROR_MESSAGE
1245         if (context != NULL)
1246                 msg = krb5_get_error_message(context, code);
1247 #endif
1248         if (msg != NULL)
1249                 return msg;
1250 #if HAVE_KRB5
1251         return error_message(code);
1252 #else
1253         if (context != NULL)
1254                 return krb5_get_err_text(context, code);
1255         else
1256                 return error_message(code);
1257 #endif
1258 }
1259
1260 /*
1261  * Return default Kerberos realm
1262  */
1263 void
1264 gssd_k5_get_default_realm(char **def_realm)
1265 {
1266         krb5_context context;
1267
1268         if (krb5_init_context(&context))
1269                 return;
1270
1271         krb5_get_default_realm(context, def_realm);
1272
1273         krb5_free_context(context);
1274 }