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