c547350928121ba922c4be5772c316aea83a210f
[openafs.git] / src / aklog / aklog.c
1 /*
2  * $Id$
3  *
4  * Copyright 1990,1991 by the Massachusetts Institute of Technology
5  * For distribution and copying rights, see the file "mit-copyright.h"
6  */
7 /*
8  * Copyright (c) 2005, 2006
9  * The Linux Box Corporation
10  * ALL RIGHTS RESERVED
11  *
12  * Permission is granted to use, copy, create derivative works
13  * and redistribute this software and such derivative works
14  * for any purpose, so long as the name of the Linux Box
15  * Corporation is not used in any advertising or publicity
16  * pertaining to the use or distribution of this software
17  * without specific, written prior authorization.  If the
18  * above copyright notice or any other identification of the
19  * Linux Box Corporation is included in any copy of any
20  * portion of this software, then the disclaimer below must
21  * also be included.
22  *
23  * This software is provided as is, without representation
24  * from the Linux Box Corporation as to its fitness for any
25  * purpose, and without warranty by the Linux Box Corporation
26  * of any kind, either express or implied, including
27  * without limitation the implied warranties of
28  * merchantability and fitness for a particular purpose.  The
29  * regents of the Linux Box Corporation shall not be liable
30  * for any damages, including special, indirect, incidental, or
31  * consequential damages, with respect to any claim arising
32  * out of or in connection with the use of the software, even
33  * if it has been or is hereafter advised of the possibility of
34  * such damages.
35  */
36
37 #include <afsconfig.h>
38
39 #include <stdio.h>
40 #include <string.h>
41 #include <ctype.h>
42 #include <sys/types.h>
43 #ifdef HAVE_UNISTD_H
44 #include <unistd.h>
45 #endif
46 #ifdef HAVE_STDLIB_H
47 #include <stdlib.h>
48 #endif
49 #ifdef HAVE_MEMORY_H
50 #include <memory.h>
51 #endif
52 #include <errno.h>
53
54 #include <sys/stat.h>
55 #include <fcntl.h>
56
57 #include <sys/param.h>
58 #include <sys/errno.h>
59 #include <netdb.h>
60 #include <sys/socket.h>
61 #include <netinet/in.h>
62 #include <arpa/inet.h>
63 #include <pwd.h>
64
65 #include <afs/stds.h>
66 #include <afs/ktc.h>
67 #include <afs/token.h>
68
69 #include <krb5.h>
70 #if defined(HAVE_ET_COM_ERR_H)
71 #include <et/com_err.h>
72 #else
73 #include <com_err.h>
74 #endif
75
76 #ifndef HAVE_KERBEROSV_HEIM_ERR_H
77 #include <afs/com_err.h>
78 #endif
79
80 #include <afs/param.h>
81 #ifdef AFS_SUN5_ENV
82 #include <sys/ioccom.h>
83 #endif
84
85 /* Prevent inclusion of des.h to avoid conflicts with des types */
86 #define NO_DES_H_INCLUDE
87
88 #include <afs/auth.h>
89 #include <afs/cellconfig.h>
90 #include <afs/vice.h>
91 #include <afs/venus.h>
92 #include <afs/ptserver.h>
93 #include <afs/ptuser.h>
94 #include <afs/pterror.h>
95 #include <afs/dirpath.h>
96 #include <afs/afsutil.h>
97
98 #include "aklog.h"
99 #include "linked_list.h"
100
101 #ifdef HAVE_KRB5_CREDS_KEYBLOCK
102 #define USING_MIT 1
103 #endif
104 #ifdef HAVE_KRB5_CREDS_SESSION
105 #define USING_HEIMDAL 1
106 #endif
107
108 #define AFSKEY "afs"
109 #define AFSINST ""
110
111 #ifndef AFS_TRY_FULL_PRINC
112 #define AFS_TRY_FULL_PRINC 1
113 #endif /* AFS_TRY_FULL_PRINC */
114
115 #define AKLOG_TRYAGAIN -1
116 #define AKLOG_SUCCESS 0
117 #define AKLOG_USAGE 1
118 #define AKLOG_SOMETHINGSWRONG 2
119 #define AKLOG_AFS 3
120 #define AKLOG_KERBEROS 4
121 #define AKLOG_TOKEN 5
122 #define AKLOG_BADPATH 6
123 #define AKLOG_MISC 7
124
125 #ifndef NULL
126 #define NULL 0
127 #endif
128
129 #ifndef TRUE
130 #define TRUE 1
131 #endif
132
133 #ifndef FALSE
134 #define FALSE 0
135 #endif
136
137 #ifndef MAXSYMLINKS
138 /* RedHat 4.x doesn't seem to define this */
139 #define MAXSYMLINKS     5
140 #endif
141
142 #define DIR '/'                 /* Character that divides directories */
143 #define DIRSTRING "/"           /* String form of above */
144 #define VOLMARKER ':'           /* Character separating cellname from mntpt */
145 #define VOLMARKERSTRING ":"     /* String form of above */
146
147 typedef struct {
148     char cell[BUFSIZ];
149     char realm[REALM_SZ];
150 } cellinfo_t;
151
152 static krb5_ccache  _krb425_ccache = NULL;
153
154 /*
155  * Why doesn't AFS provide these prototypes?
156  */
157
158 extern int pioctl(char *, afs_int32, struct ViceIoctl *, afs_int32);
159
160 /*
161  * Other prototypes
162  */
163
164 extern char *afs_realm_of_cell(krb5_context, struct afsconf_cell *, int);
165 static int isdir(char *, unsigned char *);
166 static krb5_error_code get_credv5(krb5_context context, char *, char *,
167                                   char *, krb5_creds **);
168 static int get_user_realm(krb5_context, char **);
169
170 #define TRYAGAIN(x) (x == AKLOG_TRYAGAIN || \
171                      x == KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN || \
172                      x == KRB5KRB_ERR_GENERIC)
173
174 #if defined(HAVE_KRB5_PRINC_SIZE) || defined(krb5_princ_size)
175
176 #define get_princ_str(c, p, n) krb5_princ_component(c, p, n)->data
177 #define get_princ_len(c, p, n) krb5_princ_component(c, p, n)->length
178 #define second_comp(c, p) (krb5_princ_size(c, p) > 1)
179 #define realm_data(c, p) krb5_princ_realm(c, p)->data
180 #define realm_len(c, p) krb5_princ_realm(c, p)->length
181
182 #elif defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING)
183
184 #define get_princ_str(c, p, n) krb5_principal_get_comp_string(c, p, n)
185 #define get_princ_len(c, p, n) strlen(krb5_principal_get_comp_string(c, p, n))
186 #define second_comp(c, p) (krb5_principal_get_comp_string(c, p, 1) != NULL)
187 #define realm_data(c, p) krb5_realm_data(krb5_principal_get_realm(c, p))
188 #define realm_len(c, p) krb5_realm_length(krb5_principal_get_realm(c, p))
189
190 #else
191 #error "Must have either krb5_princ_size or krb5_principal_get_comp_string"
192 #endif
193
194 #if !defined(HAVE_KRB5_ENCRYPT_TKT_PART) && defined(HAVE_ENCODE_KRB5_ENC_TKT_PART) && defined(HAVE_KRB5_C_ENCRYPT)
195 extern krb5_error_code encode_krb5_enc_tkt_part (const krb5_enc_tkt_part *rep,
196                                                  krb5_data **code);
197
198 krb5_error_code
199 krb5_encrypt_tkt_part(krb5_context context,
200                       const krb5_keyblock *key,
201                       krb5_ticket *ticket)
202 {
203     krb5_data *data = 0;
204     int code;
205     size_t enclen;
206
207     if ((code = encode_krb5_enc_tkt_part(ticket->enc_part2, &data)))
208         goto Done;
209     if ((code = krb5_c_encrypt_length(context, key->enctype,
210                                       data->length, &enclen)))
211         goto Done;
212     ticket->enc_part.ciphertext.length = enclen;
213     if (!(ticket->enc_part.ciphertext.data = malloc(enclen))) {
214         code = ENOMEM;
215         goto Done;
216     }
217     if ((code = krb5_c_encrypt(context, key, KRB5_KEYUSAGE_KDC_REP_TICKET,
218                                0, data, &ticket->enc_part))) {
219         free(ticket->enc_part.ciphertext.data);
220         ticket->enc_part.ciphertext.data = 0;
221     }
222 Done:
223     if (data) {
224         if (data->data)
225             free(data->data);
226         free(data);
227     }
228     return code;
229 }
230 #endif
231
232 #if defined(HAVE_KRB5_CREDS_KEYBLOCK)
233
234 #define get_cred_keydata(c) c->keyblock.contents
235 #define get_cred_keylen(c) c->keyblock.length
236 #define get_creds_enctype(c) c->keyblock.enctype
237
238 #elif defined(HAVE_KRB5_CREDS_SESSION)
239
240 #define get_cred_keydata(c) c->session.keyvalue.data
241 #define get_cred_keylen(c) c->session.keyvalue.length
242 #define get_creds_enctype(c) c->session.keytype
243
244 #else
245 #error "Must have either keyblock or session member of krb5_creds"
246 #endif
247
248 #if !defined(HAVE_KRB5_524_CONVERT_CREDS) && defined(HAVE_KRB524_CONVERT_CREDS_KDC)
249 #define krb5_524_convert_creds krb524_convert_creds_kdc
250 #elif !defined(HAVE_KRB5_524_CONVERT_CREDS) && !defined(HAVE_KRB524_CONVERT_CREDS_KDC)
251 #define HAVE_NO_KRB5_524
252 #endif
253
254 #if USING_HEIMDAL
255 #define deref_keyblock_enctype(kb)              \
256     ((kb)->keytype)
257
258 #define deref_entry_keyblock(entry)             \
259     entry->keyblock
260
261 #define deref_session_key(creds)                \
262     creds->session
263
264 #define deref_enc_tkt_addrs(tkt)                \
265     tkt->caddr
266
267 #define deref_enc_length(enc)                   \
268     ((enc)->cipher.length)
269
270 #define deref_enc_data(enc)                     \
271     ((enc)->cipher.data)
272
273 #define krb5_free_keytab_entry_contents krb5_kt_free_entry
274
275 #else
276 #define deref_keyblock_enctype(kb)              \
277     ((kb)->enctype)
278
279 #define deref_entry_keyblock(entry)             \
280     entry->key
281
282 #define deref_session_key(creds)                \
283     creds->keyblock
284
285 #define deref_enc_tkt_addrs(tkt)                \
286     tkt->caddrs
287
288 #define deref_enc_length(enc)                   \
289     ((enc)->ciphertext.length)
290
291 #define deref_enc_data(enc)                     \
292     ((enc)->ciphertext.data)
293
294 #endif
295
296 #define deref_entry_enctype(entry)                      \
297     deref_keyblock_enctype(&deref_entry_keyblock(entry))
298
299 /*
300  * Provide a replacement for strerror if we don't have it
301  */
302
303 #ifndef HAVE_STRERROR
304 extern char *sys_errlist[];
305 #define strerror(x) sys_errlist[x]
306 #endif /* HAVE_STRERROR */
307
308 static char *progname = NULL;   /* Name of this program */
309 static int dflag = FALSE;       /* Give debugging information */
310 static int noauth = FALSE;      /* If true, don't try to get tokens */
311 static int zsubs = FALSE;       /* Are we keeping track of zephyr subs? */
312 static int hosts = FALSE;       /* Are we keeping track of hosts? */
313 static int noprdb = FALSE;      /* Skip resolving name to id? */
314 static int linked = FALSE;      /* try for both AFS nodes */
315 static int afssetpag = FALSE;   /* setpag for AFS */
316 static int force = FALSE;       /* Bash identical tokens? */
317 static int do524 = FALSE;       /* Should we do 524 instead of rxkad2b? */
318 static char *keytab = NULL;     /* keytab for akimpersonate */
319 static char *client = NULL;     /* client principal for akimpersonate */
320 static linked_list zsublist;    /* List of zephyr subscriptions */
321 static linked_list hostlist;    /* List of host addresses */
322 static linked_list authedcells; /* List of cells already logged to */
323
324 /* A com_error bodge. The idea here is that this routine lets us lookup
325  * things in the system com_err, if the AFS one just tells us the error
326  * is unknown
327  */
328
329 void
330 redirect_errors(const char *who, afs_int32 code, const char *fmt, va_list ap)
331 {
332     if (who) {
333         fputs(who, stderr);
334         fputs(": ", stderr);
335     }
336     if (code) {
337         const char *str = afs_error_message(code);
338         if (strncmp(str, "unknown", strlen("unknown")) == 0) {
339 #ifdef HAVE_KRB5_SVC_GET_MSG
340             krb5_svc_get_msg(code,&str);
341 #elif defined(HAVE_ERROR_MESSAGE)
342             str = error_message(code);
343 #else
344             ; /* IRIX apparently has neither: use the string we have */
345 #endif
346         }
347         fputs(str, stderr);
348         fputs(" ", stderr);
349 #ifdef HAVE_KRB5_SVC_GET_MSG
350         krb5_free_string(str);
351 #endif
352     }
353     if (fmt) {
354         vfprintf(stderr, fmt, ap);
355     }
356     putc('\n', stderr);
357     fflush(stderr);
358 }
359
360 static void
361 afs_dprintf(char *fmt, ...) {
362     va_list ap;
363
364     va_start(ap, fmt);
365     if (dflag)
366         vprintf(fmt, ap);
367     va_end(ap);
368 }
369
370 static char *
371 copy_cellinfo(cellinfo_t *cellinfo)
372 {
373     cellinfo_t *new_cellinfo;
374
375     if ((new_cellinfo = (cellinfo_t *)malloc(sizeof(cellinfo_t))))
376         memcpy(new_cellinfo, cellinfo, sizeof(cellinfo_t));
377
378     return ((char *)new_cellinfo);
379 }
380
381
382 static int
383 get_cellconfig(char *cell, struct afsconf_cell *cellconfig, char **local_cell)
384 {
385     int status = AKLOG_SUCCESS;
386     struct afsconf_dir *configdir;
387
388     memset(cellconfig, 0, sizeof(*cellconfig));
389
390     *local_cell = malloc(MAXCELLCHARS);
391     if (*local_cell == NULL) {
392         fprintf(stderr, "%s: can't allocate memory for local cell name\n",
393                 progname);
394         exit(AKLOG_AFS);
395     }
396
397     if (!(configdir = afsconf_Open(AFSDIR_CLIENT_ETC_DIRPATH))) {
398         fprintf(stderr,
399                 "%s: can't get afs configuration (afsconf_Open(%s))\n",
400                 progname, AFSDIR_CLIENT_ETC_DIRPATH);
401         exit(AKLOG_AFS);
402     }
403
404     if (afsconf_GetLocalCell(configdir, *local_cell, MAXCELLCHARS)) {
405         fprintf(stderr, "%s: can't determine local cell.\n", progname);
406         exit(AKLOG_AFS);
407     }
408
409     if ((cell == NULL) || (cell[0] == 0))
410         cell = *local_cell;
411
412     /* XXX - This function modifies 'cell' by passing it through lcstring */
413     if (afsconf_GetCellInfo(configdir, cell, NULL, cellconfig)) {
414         fprintf(stderr, "%s: Can't get information about cell %s.\n",
415                 progname, cell);
416         status = AKLOG_AFS;
417     }
418
419     afsconf_Close(configdir);
420
421     return(status);
422 }
423
424 static char *
425 extract_realm(krb5_context context, krb5_principal princ) {
426     int len;
427     char *realm;
428
429     len = realm_len(context, princ);
430     if (len > REALM_SZ-1)
431         len = REALM_SZ-1;
432
433     realm = malloc(sizeof(char) * (len+1));
434     if (realm == NULL)
435         return NULL;
436
437     strncpy(realm, realm_data(context, princ), len);
438     realm[len] = '\0';
439
440     return realm;
441 }
442
443 static int
444 get_realm_from_cred(krb5_context context, krb5_creds *v5cred, char **realm) {
445 #if !defined(HEIMDAL) && defined(HAVE_KRB5_DECODE_TICKET)
446     krb5_error_code code;
447     krb5_ticket *ticket;
448
449     *realm = NULL;
450
451     code = krb5_decode_ticket(&v5cred->ticket, &ticket);
452     if (code)
453         return code;
454
455     *realm = extract_realm(context, ticket->server);
456     if (*realm == NULL)
457         code = ENOMEM;
458
459     krb5_free_ticket(context, ticket);
460
461     return code;
462 #else
463     *realm = NULL;
464     return 0;
465 #endif
466 }
467
468 /*!
469  * Get a Kerberos service ticket to use as the base of an rxkad token for
470  * a given AFS cell.
471  *
472  * @param[in] context
473  *      An initialized Kerberos v5 context
474  * @param[in] realm
475  *      The realm to look in for the service principal. If NULL, then the
476  *      realm is determined from the cell name or the user's credentials
477  *      (see below for the heuristics used)
478  * @param[in] cell
479  *      The cell information for the cell to obtain a ticket for
480  * @param[out] v5cred
481  *      A Kerberos credentials structure containing the ticket acquired
482  *      for the cell. This is a dynamically allocated structure, which
483  *      should be freed by using the appropriate Kerberos API function.
484  * @param[out] realmUsed
485  *      The realm in which the cell's service principal was located. If
486  *      unset, then the principal was located in the same realm as the
487  *      current user. This is a malloc'd string which should be freed
488  *      by the caller.
489  *
490  * @returns
491  *      0 on success, an error value upon failure
492  *
493  * @notes
494  *      This code tries principals in the following, much debated,
495  *      order:
496  *
497  *      If the realm is specified on the command line we do
498  *         - afs/cell@COMMAND-LINE-REALM
499  *         - afs@COMMAND-LINE-REALM
500  *
501  *      Otherwise, we do
502  *         - afs/cell@REALM-FROM-USERS-PRINCIPAL
503  *         - afs/cell@krb5_get_host_realm(db-server)
504  *        Then, if krb5_get_host_realm(db-server) is non-empty
505  *           - afs@ krb5_get_host_realm(db-server)
506  *        Otherwise
507  *           - afs/cell@ upper-case-domain-of-db-server
508  *           - afs@ upper-case-domain-of-db-server
509  *
510  *      In all cases, the 'afs@' variant is only tried where the
511  *      cell and the realm match case-insensitively.
512  */
513
514 static int
515 rxkad_get_ticket(krb5_context context, char *realm,
516                  struct afsconf_cell *cell,
517                  krb5_creds **v5cred, char **realmUsed) {
518     char *realm_of_cell = NULL;
519     char *realm_of_user = NULL;
520     char *realm_from_princ = NULL;
521     int status;
522     int retry;
523
524     *realmUsed = NULL;
525
526     if ((status = get_user_realm(context, &realm_of_user))) {
527         fprintf(stderr, "%s: Couldn't determine realm of user:", progname);
528         afs_com_err(progname, status, " while getting realm");
529         status = AKLOG_KERBEROS;
530         goto out;
531     }
532
533     retry = 1;
534
535     while(retry) {
536         /* Cell on command line - use that one */
537         if (realm && realm[0]) {
538             realm_of_cell = realm;
539             status = AKLOG_TRYAGAIN;
540             afs_dprintf("We were told to authenticate to realm %s.\n", realm);
541         } else {
542             /* Initially, try using afs/cell@USERREALM */
543             afs_dprintf("Trying to authenticate to user's realm %s.\n",
544                     realm_of_user);
545             realm_of_cell = realm_of_user;
546             status = get_credv5(context, AFSKEY, cell->name, realm_of_cell,
547                                 v5cred);
548
549             /* If that failed, try to determine the realm from the name of
550              * one of the DB servers */
551             if (TRYAGAIN(status)) {
552                 realm_of_cell = afs_realm_of_cell(context, cell, FALSE);
553                 if (!realm_of_cell) {
554                     fprintf(stderr, "%s: Couldn't figure out realm for cell "
555                             "%s.\n", progname, cell->name);
556                     exit(AKLOG_MISC);
557                 }
558
559                 if (realm_of_cell[0])
560                     afs_dprintf("We've deduced that we need to authenticate"
561                             " to realm %s.\n", realm_of_cell);
562                     else
563                     afs_dprintf("We've deduced that we need to authenticate "
564                             "using referrals.\n");
565             }
566         }
567
568         if (TRYAGAIN(status)) {
569             /* If we've got the full-princ-first option, or we're in a
570              * different realm from the cell - use the cell name as the
571              * instance */
572             if (AFS_TRY_FULL_PRINC ||
573                 strcasecmp(cell->name, realm_of_cell)!=0) {
574                 status = get_credv5(context, AFSKEY, cell->name,
575                                     realm_of_cell, v5cred);
576
577                 /* If we failed & we've got an empty realm, then try
578                  * calling afs_realm_for_cell again. */
579                 if (TRYAGAIN(status) && !realm_of_cell[0]) {
580                     /* This time, get the realm by taking the domain
581                      * component of the db server and make it upper case */
582                     realm_of_cell = afs_realm_of_cell(context, cell, TRUE);
583                     if (!realm_of_cell) {
584                         fprintf(stderr,
585                                 "%s: Couldn't figure out realm for cell %s.\n",
586                                 progname, cell->name);
587                         exit(AKLOG_MISC);
588                     }
589                     afs_dprintf("We've deduced that we need to authenticate"
590                             " to realm %s.\n", realm_of_cell);
591                 }
592                 status = get_credv5(context, AFSKEY, cell->name,
593                                     realm_of_cell, v5cred);
594             }
595
596             /* If the realm and cell name match, then try without an
597              * instance, but only if realm is non-empty */
598
599             if (TRYAGAIN(status) &&
600                 strcasecmp(cell->name, realm_of_cell) == 0) {
601                 status = get_credv5(context, AFSKEY, NULL, realm_of_cell,
602                                     v5cred);
603                 if (!AFS_TRY_FULL_PRINC && TRYAGAIN(status)) {
604                     status = get_credv5(context, AFSKEY, cell->name,
605                                         realm_of_cell, v5cred);
606                 }
607             }
608         }
609
610         /* Try to find a service principal for this cell.
611          * Some broken MIT libraries return KRB5KRB_AP_ERR_MSG_TYPE upon
612          * the first attempt, so we try twice to be sure */
613
614         if (status == KRB5KRB_AP_ERR_MSG_TYPE && retry == 1)
615             retry++;
616         else
617             retry = 0;
618     }
619
620     if (status != 0) {
621         afs_dprintf("Kerberos error code returned by get_cred : %d\n", status);
622         fprintf(stderr, "%s: Couldn't get %s AFS tickets:\n",
623                 progname, cell->name);
624         afs_com_err(progname, status, "while getting AFS tickets");
625 #ifdef KRB5_CC_NOT_KTYPE
626         if (status == KRB5_CC_NOT_KTYPE) {
627             fprintf(stderr, "allow_weak_enctypes may be required in the Kerberos configuration\n");
628         }
629 #endif
630         status = AKLOG_KERBEROS;
631         goto out;
632     }
633
634     /* If we've got a valid ticket, and we still don't know the realm name
635      * try to figure it out from the contents of the ticket
636      */
637     if (strcmp(realm_of_cell, "") == 0) {
638         status = get_realm_from_cred(context, *v5cred, &realm_from_princ);
639         if (status) {
640             fprintf(stderr,
641                     "%s: Couldn't decode ticket to determine realm for "
642                     "cell %s.\n",
643                     progname, cell->name);
644         } else {
645             if (realm_from_princ)
646                 realm_of_cell = realm_from_princ;
647         }
648     }
649
650     /* If the realm of the user and cell differ, then we need to use the
651      * realm when we later construct the user's principal */
652     if (realm_of_cell != NULL && strcmp(realm_of_user, realm_of_cell) != 0)
653         *realmUsed = realm_of_user;
654
655 out:
656     if (realm_from_princ)
657         free(realm_from_princ);
658     if (realm_of_user && *realmUsed == NULL)
659         free(realm_of_user);
660
661     return status;
662 }
663
664 /*!
665  * Build an rxkad token from a Kerberos ticket, using only local tools (that
666  * is, without using a 524 conversion service)
667  *
668  * @param[in] context
669  *      An initialised Kerberos 5 context
670  * @param[in] v5cred
671  *      A Kerberos credentials structure containing a suitable service ticket
672  * @param[out] tokenPtr
673  *      An AFS token structure containing an rxkad token. This is a malloc'd
674  *      structure which should be freed by the caller.
675  * @param[out[ userPtr
676  *      A string containing the principal of the user to whom the token was
677  *      issued. This is a malloc'd block which should be freed by the caller.
678  *
679  * @returns
680  *      0 on success, an error value upon failure
681  */
682 static int
683 rxkad_build_native_token(krb5_context context, krb5_creds *v5cred,
684                          struct ktc_tokenUnion **tokenPtr, char **userPtr) {
685     char username[BUFSIZ];
686     struct ktc_tokenUnion *token;
687     struct token_rxkad *rxkadToken;
688 #ifdef HAVE_NO_KRB5_524
689     char *p;
690     int len;
691 #else
692     int status;
693     char k4name[ANAME_SZ];
694     char k4inst[INST_SZ];
695     char k4realm[REALM_SZ];
696 #endif
697
698     afs_dprintf("Using Kerberos V5 ticket natively\n");
699
700     *tokenPtr = NULL;
701     *userPtr = NULL;
702
703 #ifndef HAVE_NO_KRB5_524
704     status = krb5_524_conv_principal (context, v5cred->client,
705                                       (char *) &k4name,
706                                       (char *) &k4inst,
707                                       (char *) &k4realm);
708     if (status) {
709         afs_com_err(progname, status, "while converting principal "
710                     "to Kerberos V4 format");
711         return AKLOG_KERBEROS;
712     }
713     strcpy (username, k4name);
714     if (k4inst[0]) {
715         strcat (username, ".");
716         strcat (username, k4inst);
717     }
718 #else
719     len = min(get_princ_len(context, v5cred->client, 0),
720               second_comp(context, v5cred->client) ?
721               MAXKTCNAMELEN - 2 : MAXKTCNAMELEN - 1);
722     strncpy(username, get_princ_str(context, v5cred->client, 0), len);
723     username[len] = '\0';
724
725     if (second_comp(context, v5cred->client)) {
726         strcat(username, ".");
727         p = username + strlen(username);
728         len = min(get_princ_len(context, v5cred->client, 1),
729                   MAXKTCNAMELEN - strlen(username) - 1);
730         strncpy(p, get_princ_str(context, v5cred->client, 1), len);
731         p[len] = '\0';
732     }
733 #endif
734
735     token = malloc(sizeof(struct ktc_tokenUnion));
736     if (token == NULL)
737         return ENOMEM;
738
739     memset(token, 0, sizeof(struct ktc_tokenUnion));
740
741     token->at_type = AFSTOKEN_UNION_KAD;
742     rxkadToken = &token->ktc_tokenUnion_u.at_kad;
743
744     rxkadToken->rk_kvno = RXKAD_TKT_TYPE_KERBEROS_V5;
745     rxkadToken->rk_begintime = v5cred->times.starttime;;
746     rxkadToken->rk_endtime = v5cred->times.endtime;
747     memcpy(&rxkadToken->rk_key, get_cred_keydata(v5cred),
748            get_cred_keylen(v5cred));
749     rxkadToken->rk_ticket.rk_ticket_len = v5cred->ticket.length;
750     rxkadToken->rk_ticket.rk_ticket_val = malloc(v5cred->ticket.length);
751     if (rxkadToken->rk_ticket.rk_ticket_val == NULL) {
752         free(token);
753         return ENOMEM;
754     }
755     memcpy(rxkadToken->rk_ticket.rk_ticket_val, v5cred->ticket.data,
756            rxkadToken->rk_ticket.rk_ticket_len);
757
758     *tokenPtr = token;
759     *userPtr = strdup(username);
760
761     return 0;
762 }
763
764 /*!
765  * Convert a Keberos ticket to an rxkad token, using information obtained
766  * from an external Kerberos 5->4 conversion service. If the code is built
767  * with HAVE_NO_KRB5_524 then this is a stub function which will always
768  * return success without a token.
769  *
770  * @param[in] context
771  *      An initialised Kerberos 5 context
772  * @param[in] v5cred
773  *      A Kerberos credentials structure containing a suitable service ticket
774  * @param[out] tokenPtr
775  *      An AFS token structure containing an rxkad token. This is a malloc'd
776  *      structure which should be freed by the caller.
777  * @param[out[ userPtr
778  *      A string containing the principal of the user to whom the token was
779  *      issued. This is a malloc'd block which should be freed by the caller.
780  *
781  * @returns
782  *      0 on success, an error value upon failure
783  */
784
785 #ifdef HAVE_NO_KRB5_524
786 static int
787 rxkad_get_converted_token(krb5_context context, krb5_creds *v5cred,
788                           struct ktc_tokenUnion **tokenPtr, char **userPtr) {
789     *tokenPtr = NULL;
790     *userPtr = NULL;
791
792     return 0;
793 }
794 #else
795 static int
796 rxkad_get_converted_token(krb5_context context, krb5_creds *v5cred,
797                           struct ktc_tokenUnion **tokenPtr, char **userPtr) {
798     CREDENTIALS cred;
799     char username[BUFSIZ];
800     struct ktc_tokenUnion *token;
801     struct token_rxkad *rxkadToken;
802     int status;
803
804     *tokenPtr = NULL;
805     *userPtr = NULL;
806
807     afs_dprintf("Using Kerberos 524 translator service\n");
808
809     status = krb5_524_convert_creds(context, v5cred, &cred);
810
811     if (status) {
812         afs_com_err(progname, status, "while converting tickets "
813                 "to Kerberos V4 format");
814         return AKLOG_KERBEROS;
815     }
816
817     strcpy (username, cred.pname);
818     if (cred.pinst[0]) {
819         strcat (username, ".");
820         strcat (username, cred.pinst);
821     }
822
823     token = malloc(sizeof(struct ktc_tokenUnion));
824     if (token == NULL)
825         return ENOMEM;
826     memset(token, 0, sizeof(struct ktc_tokenUnion));
827
828     token->at_type = AFSTOKEN_UNION_KAD;
829
830     rxkadToken = &token->ktc_tokenUnion_u.at_kad;
831     rxkadToken->rk_kvno = cred.kvno;
832     rxkadToken->rk_begintime = cred.issue_date;
833     /*
834      * It seems silly to go through a bunch of contortions to
835      * extract the expiration time, when the v5 credentials already
836      * has the exact time!  Let's use that instead.
837      *
838      * Note that this isn't a security hole, as the expiration time
839      * is also contained in the encrypted token
840      */
841     rxkadToken->rk_endtime = v5cred->times.endtime;
842     memcpy(&rxkadToken->rk_key, cred.session, 8);
843     rxkadToken->rk_ticket.rk_ticket_len = cred.ticket_st.length;
844     rxkadToken->rk_ticket.rk_ticket_val = malloc(cred.ticket_st.length);
845     if (rxkadToken->rk_ticket.rk_ticket_val == NULL) {
846         free(token);
847         return ENOMEM;
848     }
849     memcpy(rxkadToken->rk_ticket.rk_ticket_val, cred.ticket_st.dat,
850            rxkadToken->rk_ticket.rk_ticket_len);
851
852     *tokenPtr = token;
853     *userPtr = strdup(username);
854
855     return 0;
856 }
857 #endif
858
859 /*!
860  * This function gets an rxkad token for a given cell.
861  *
862  * @param[in] context
863  *      An initialized Kerberos v5 context
864  * @param[in] cell
865  *      The cell information for the cell which we're obtaining a token for
866  * @param[in] realm
867  *      The realm to look in for the service principal. If NULL, then the
868  *      realm is determined from the cell name or the user's credentials
869  *      (see the documentation for rxkad_get_ticket)
870  * @param[out] token
871  *      The rxkad token produced. This is a malloc'd structure which should
872  *      be freed by the caller.
873  * @parma[out] authuser
874  *      A string containing the principal of the user to whom the token was
875  *      issued. This is a malloc'd block which should be freed by the caller.
876  * @param[out] foreign
877  *      Whether the user is considered as 'foreign' to the realm of the cell.
878  *
879  * @returns
880  *      0 on success, an error value upon failuer
881  */
882 static int
883 rxkad_get_token(krb5_context context, struct afsconf_cell *cell, char *realm,
884                 struct ktc_tokenUnion **token, char **authuser, int *foreign) {
885     krb5_creds *v5cred;
886     char *realmUsed = NULL;
887     char *username = NULL;
888     int status;
889     size_t len;
890
891     *token = NULL;
892     *authuser = NULL;
893     *foreign = 0;
894
895     status = rxkad_get_ticket(context, realm, cell, &v5cred, &realmUsed);
896     if (status)
897         return status;
898
899     if (do524)
900         status = rxkad_get_converted_token(context, v5cred, token, &username);
901     else
902         status = rxkad_build_native_token(context, v5cred, token, &username);
903
904     if (status)
905         goto out;
906
907     /* We now have the username, plus the realm name, so stitch them together
908      * to give us the name that the ptserver will know the user by */
909     if (realmUsed == NULL) {
910         *authuser = username;
911         username = NULL;
912         *foreign = 0;
913     } else {
914         len = strlen(username)+strlen(realmUsed)+2;
915         *authuser = malloc(len);
916         afs_snprintf(*authuser, len, "%s@%s", username, realmUsed);
917         *foreign = 1;
918     }
919
920 out:
921     if (realmUsed)
922         free(realmUsed);
923     if (username)
924         free(username);
925
926     return status;
927 }
928
929 /* 
930  * Log to a cell.  If the cell has already been logged to, return without
931  * doing anything.  Otherwise, log to it and mark that it has been logged
932  * to.
933  */
934 static int
935 auth_to_cell(krb5_context context, char *cell, char *realm, char **linkedcell)
936 {
937     int status = AKLOG_SUCCESS;
938     int isForeign = 0;
939     char *username = NULL;      /* To hold client username structure */
940     afs_int32 viceId;           /* AFS uid of user */
941
942     char *local_cell = NULL;
943     struct ktc_tokenUnion *rxkadToken = NULL;
944     struct ktc_setTokenData *token;
945     struct ktc_setTokenData *btoken = NULL;
946     struct afsconf_cell cellconf;
947
948     /* NULL or empty cell returns information on local cell */
949     if ((status = get_cellconfig(cell, &cellconf, &local_cell)))
950         return(status);
951
952     if (linkedcell != NULL) {
953         if (cellconf.linkedCell != NULL) {
954             *linkedcell = strdup(cellconf.linkedCell);
955             if (*linkedcell == NULL) {
956                 status = ENOMEM;
957                 goto out;
958             }
959         } else {
960             *linkedcell = NULL;
961         }
962     }
963
964     if (ll_string(&authedcells, ll_s_check, cellconf.name)) {
965         afs_dprintf("Already authenticated to %s (or tried to)\n", cellconf.name);
966         status = AKLOG_SUCCESS;
967         goto out;
968     }
969
970     /*
971      * Record that we have attempted to log to this cell.  We do this
972      * before we try rather than after so that we will not try
973      * and fail repeatedly for one cell.
974      */
975     ll_string(&authedcells, ll_s_add, cellconf.name);
976
977     /*
978      * Record this cell in the list of zephyr subscriptions.  We may
979      * want zephyr subscriptions even if authentication fails.
980      * If this is done after we attempt to get tokens, aklog -zsubs
981      * can return something different depending on whether or not we
982      * are in -noauth mode.
983      */
984     if (ll_string(&zsublist, ll_s_add, cellconf.name) == LL_FAILURE) {
985         fprintf(stderr,
986                 "%s: failure adding cell %s to zephyr subscriptions list.\n",
987                 progname, cellconf.name);
988         exit(AKLOG_MISC);
989     }
990     if (ll_string(&zsublist, ll_s_add, local_cell) == LL_FAILURE) {
991         fprintf(stderr,
992                 "%s: failure adding cell %s to zephyr subscriptions list.\n",
993                 progname, local_cell);
994         exit(AKLOG_MISC);
995     }
996
997     if (!noauth) {
998         afs_dprintf("Authenticating to cell %s (server %s).\n", cellconf.name,
999                 cellconf.hostName[0]);
1000
1001         token = token_buildTokenJar(cellconf.name);
1002         if (token == NULL) {
1003             status = ENOMEM;
1004             goto out;
1005         }
1006
1007         status = rxkad_get_token(context, &cellconf, realm, &rxkadToken,
1008                                  &username, &isForeign);
1009         if (status)
1010             goto out;
1011
1012         /* We need to keep the token structure around so that we can stick
1013          * the viceId into it (once we know it) */
1014         status = token_addToken(token, rxkadToken);
1015         if (status) {
1016             afs_dprintf("Add Token failed with %d", status);
1017             goto out;
1018         }
1019
1020         if (!force &&
1021             ktc_GetTokenEx(cellconf.name, &btoken) == 0 &&
1022             token_SetsEquivalent(token, btoken)) {
1023
1024             token_FreeSet(&btoken);
1025             afs_dprintf("Identical tokens already exist; skipping.\n");
1026             status = AKLOG_SUCCESS;
1027             goto out;
1028         }
1029
1030         if (btoken)
1031             token_FreeSet(&btoken);
1032
1033 #ifdef FORCE_NOPRDB
1034         noprdb = 1;
1035 #endif
1036
1037         if (noprdb) {
1038             afs_dprintf("Not resolving name %s to id (-noprdb set)\n", username);
1039         }
1040         else {
1041             afs_dprintf("About to resolve name %s to id in cell %s.\n", username,
1042                     cellconf.name);
1043
1044             if (!pr_Initialize (0,  AFSDIR_CLIENT_ETC_DIRPATH, cellconf.name))
1045                 status = pr_SNameToId (username, &viceId);
1046
1047             if (status)
1048                 afs_dprintf("Error %d\n", status);
1049             else
1050                 afs_dprintf("Id %d\n", (int) viceId);
1051
1052
1053             /*
1054              * This code is taken from cklog -- it lets people
1055              * automatically register with the ptserver in foreign cells
1056              */
1057
1058 #ifdef ALLOW_REGISTER
1059             if ((status == 0) && (viceId == ANONYMOUSID) && isForeign) {
1060                 afs_dprintf("doing first-time registration of %s at %s\n",
1061                         username, cellconf.name);
1062                 viceId = 0;
1063
1064                 status = ktc_SetTokenEx(token);
1065                 if (status) {
1066                     afs_com_err(progname, status,
1067                                 "while obtaining tokens for cell %s",
1068                                 cellconf.name);
1069                     status = AKLOG_TOKEN;
1070                 }
1071
1072                 /*
1073                  * In case you're wondering, we don't need to change the
1074                  * filename here because we're still connecting to the
1075                  * same cell -- we're just using a different authenticat ion
1076                  * level
1077                  */
1078
1079                 if ((status = pr_Initialize(1L,  AFSDIR_CLIENT_ETC_DIRPATH,
1080                                             cellconf.name))) {
1081                     printf("Error %d\n", status);
1082                 }
1083
1084                 if ((status = pr_CreateUser(username, &viceId))) {
1085                     fprintf(stderr, "%s: %s so unable to create remote PTS "
1086                             "user %s in cell %s (status: %d).\n", progname,
1087                             afs_error_message(status), username, cellconf.name,
1088                             status);
1089                     viceId = ANONYMOUSID;
1090                 } else {
1091                     printf("created cross-cell entry for %s (Id %d) at %s\n",
1092                            username, viceId, cellconf.name);
1093                 }
1094             }
1095 #endif /* ALLOW_REGISTER */
1096
1097             if ((status == 0) && (viceId != ANONYMOUSID)) {
1098                 rxkadToken->ktc_tokenUnion_u.at_kad.rk_viceid = viceId;
1099                 token_replaceToken(token, rxkadToken);
1100             }
1101         }
1102
1103         afs_dprintf("Setting tokens. %s @ %s \n", username, cellconf.name);
1104
1105 #ifndef AFS_AIX51_ENV
1106         /* on AIX 4.1.4 with AFS 3.4a+ if a write is not done before
1107          * this routine, it will not add the token. It is not clear what
1108          * is going on here! So we will do the following operation.
1109          * On AIX 5, it causes the parent program to die, so we won't.
1110          */
1111         write(2,"",0); /* dummy write */
1112 #endif
1113         token_setPag(token, afssetpag);
1114         status = ktc_SetTokenEx(token);
1115         if (status) {
1116             afs_com_err(progname, status, "while setting tokens for cell %s",
1117                         cellconf.name);
1118             status = AKLOG_TOKEN;
1119         }
1120     }
1121     else
1122         afs_dprintf("Noauth mode; not authenticating.\n");
1123
1124 out:
1125     if (rxkadToken) {
1126         free(rxkadToken->ktc_tokenUnion_u.at_kad.rk_ticket.rk_ticket_val);
1127         free(rxkadToken);
1128     }
1129
1130     if (local_cell)
1131         free(local_cell);
1132     if (username)
1133         free(username);
1134
1135     return(status);
1136 }
1137
1138 static int
1139 get_afs_mountpoint(char *file, char *mountpoint, int size)
1140 {
1141 #ifdef AFS_SUN_ENV
1142     char V ='V'; /* AFS has problem on Sun with pioctl */
1143 #endif
1144     char our_file[MAXPATHLEN + 1];
1145     char *parent_dir;
1146     char *last_component;
1147     struct ViceIoctl vio;
1148     char cellname[BUFSIZ];
1149
1150     memset(our_file, 0, sizeof(our_file));
1151     strcpy(our_file, file);
1152
1153     if ((last_component = strrchr(our_file, DIR))) {
1154         *last_component++ = 0;
1155         parent_dir = our_file;
1156     }
1157     else {
1158         last_component = our_file;
1159         parent_dir = ".";
1160     }
1161
1162     memset(cellname, 0, sizeof(cellname));
1163
1164     vio.in = last_component;
1165     vio.in_size = strlen(last_component)+1;
1166     vio.out_size = size;
1167     vio.out = mountpoint;
1168
1169     if (!pioctl(parent_dir, VIOC_AFS_STAT_MT_PT, &vio, 0)) {
1170         if (strchr(mountpoint, VOLMARKER) == NULL) {
1171             vio.in = file;
1172             vio.in_size = strlen(file) + 1;
1173             vio.out_size = sizeof(cellname);
1174             vio.out = cellname;
1175
1176             if (!pioctl(file, VIOC_FILE_CELL_NAME, &vio, 1)) {
1177                 strcat(cellname, VOLMARKERSTRING);
1178                 strcat(cellname, mountpoint + 1);
1179                 memset(mountpoint + 1, 0, size - 1);
1180                 strcpy(mountpoint + 1, cellname);
1181             }
1182         }
1183         return(TRUE);
1184     }
1185     else
1186         return(FALSE);
1187 }
1188
1189 /*
1190  * This routine each time it is called returns the next directory
1191  * down a pathname.  It resolves all symbolic links.  The first time
1192  * it is called, it should be called with the name of the path
1193  * to be descended.  After that, it should be called with the arguemnt
1194  * NULL.
1195  */
1196 static char *
1197 next_path(char *origpath)
1198 {
1199     static char path[MAXPATHLEN + 1];
1200     static char pathtocheck[MAXPATHLEN + 1];
1201
1202     int link = FALSE;           /* Is this a symbolic link? */
1203     char linkbuf[MAXPATHLEN + 1];
1204     char tmpbuf[MAXPATHLEN + 1];
1205
1206     static char *last_comp;     /* last component of directory name */
1207     static char *elast_comp;    /* End of last component */
1208     char *t;
1209     int len;
1210
1211     static int symlinkcount = 0; /* We can't exceed MAXSYMLINKS */
1212
1213     /* If we are given something for origpath, we are initializing only. */
1214     if (origpath) {
1215         memset(path, 0, sizeof(path));
1216         memset(pathtocheck, 0, sizeof(pathtocheck));
1217         strcpy(path, origpath);
1218         last_comp = path;
1219         symlinkcount = 0;
1220         return(NULL);
1221     }
1222
1223     /* We were not given origpath; find then next path to check */
1224
1225     /* If we've gotten all the way through already, return NULL */
1226     if (last_comp == NULL)
1227         return(NULL);
1228
1229     do {
1230         while (*last_comp == DIR)
1231             strncat(pathtocheck, last_comp++, 1);
1232         len = (elast_comp = strchr(last_comp, DIR))
1233             ? elast_comp - last_comp : strlen(last_comp);
1234         strncat(pathtocheck, last_comp, len);
1235         memset(linkbuf, 0, sizeof(linkbuf));
1236         if ((link = (readlink(pathtocheck, linkbuf,
1237                                     sizeof(linkbuf)) > 0))) {
1238             if (++symlinkcount > MAXSYMLINKS) {
1239                 fprintf(stderr, "%s: %s\n", progname, strerror(ELOOP));
1240                 exit(AKLOG_BADPATH);
1241             }
1242             memset(tmpbuf, 0, sizeof(tmpbuf));
1243             if (elast_comp)
1244                 strcpy(tmpbuf, elast_comp);
1245             if (linkbuf[0] == DIR) {
1246                 /*
1247                  * If this is a symbolic link to an absolute path,
1248                  * replace what we have by the absolute path.
1249                  */
1250                 memset(path, 0, strlen(path));
1251                 memcpy(path, linkbuf, sizeof(linkbuf));
1252                 strcat(path, tmpbuf);
1253                 last_comp = path;
1254                 elast_comp = NULL;
1255                 memset(pathtocheck, 0, sizeof(pathtocheck));
1256             }
1257             else {
1258                 /*
1259                  * If this is a symbolic link to a relative path,
1260                  * replace only the last component with the link name.
1261                  */
1262                 strncpy(last_comp, linkbuf, strlen(linkbuf) + 1);
1263                 strcat(path, tmpbuf);
1264                 elast_comp = NULL;
1265                 if ((t = strrchr(pathtocheck, DIR))) {
1266                     t++;
1267                     memset(t, 0, strlen(t));
1268                 }
1269                 else
1270                     memset(pathtocheck, 0, sizeof(pathtocheck));
1271             }
1272         }
1273         else
1274             last_comp = elast_comp;
1275     }
1276     while(link);
1277
1278     return(pathtocheck);
1279 }
1280
1281 static void
1282 add_hosts(char *file)
1283 {
1284 #ifdef AFS_SUN_ENV
1285     char V = 'V'; /* AFS has problem on SunOS */
1286 #endif
1287     struct ViceIoctl vio;
1288     char outbuf[BUFSIZ];
1289     long *phosts;
1290     int i;
1291     struct hostent *hp;
1292     struct in_addr in;
1293
1294     memset(outbuf, 0, sizeof(outbuf));
1295
1296     vio.out_size = sizeof(outbuf);
1297     vio.in_size = 0;
1298     vio.out = outbuf;
1299
1300     afs_dprintf("Getting list of hosts for %s\n", file);
1301
1302     /* Don't worry about errors. */
1303     if (!pioctl(file, VIOCWHEREIS, &vio, 1)) {
1304         phosts = (long *) outbuf;
1305
1306         /*
1307          * Lists hosts that we care about.  If ALLHOSTS is defined,
1308          * then all hosts that you ever may possible go through are
1309          * included in this list.  If not, then only hosts that are
1310          * the only ones appear.  That is, if a volume you must use
1311          * is replaced on only one server, that server is included.
1312          * If it is replicated on many servers, then none are included.
1313          * This is not perfect, but the result is that people don't
1314          * get subscribed to a lot of instances of FILSRV that they
1315          * probably won't need which reduces the instances of
1316          * people getting messages that don't apply to them.
1317          */
1318 #ifndef ALLHOSTS
1319         if (phosts[1] != '\0')
1320             return;
1321 #endif
1322         for (i = 0; phosts[i]; i++) {
1323             if (hosts) {
1324                 in.s_addr = phosts[i];
1325                 afs_dprintf("Got host %s\n", inet_ntoa(in));
1326                 ll_string(&hostlist, ll_s_add, (char *)inet_ntoa(in));
1327             }
1328             if (zsubs && (hp=gethostbyaddr((char *) &phosts[i],sizeof(long),AF_INET))) {
1329                 afs_dprintf("Got host %s\n", hp->h_name);
1330                 ll_string(&zsublist, ll_s_add, hp->h_name);
1331             }
1332         }
1333     }
1334 }
1335
1336 /*
1337  * This routine descends through a path to a directory, logging to
1338  * every cell it encounters along the way.
1339  */
1340 static int
1341 auth_to_path(krb5_context context, char *path)
1342 {
1343     int status = AKLOG_SUCCESS;
1344     int auth_status = AKLOG_SUCCESS;
1345
1346     char *nextpath;
1347     char pathtocheck[MAXPATHLEN + 1];
1348     char mountpoint[MAXPATHLEN + 1];
1349
1350     char *cell;
1351     char *endofcell;
1352
1353     u_char isdirectory;
1354
1355     /* Initialize */
1356     if (path[0] == DIR)
1357         strcpy(pathtocheck, path);
1358     else {
1359         if (getcwd(pathtocheck, sizeof(pathtocheck)) == NULL) {
1360             fprintf(stderr, "Unable to find current working directory:\n");
1361             fprintf(stderr, "%s\n", pathtocheck);
1362             fprintf(stderr, "Try an absolute pathname.\n");
1363             exit(AKLOG_BADPATH);
1364         }
1365         else {
1366             strcat(pathtocheck, DIRSTRING);
1367             strcat(pathtocheck, path);
1368         }
1369     }
1370     next_path(pathtocheck);
1371
1372     /* Go on to the next level down the path */
1373     while ((nextpath = next_path(NULL))) {
1374         strcpy(pathtocheck, nextpath);
1375         afs_dprintf("Checking directory %s\n", pathtocheck);
1376         /*
1377          * If this is an afs mountpoint, determine what cell from
1378          * the mountpoint name which is of the form
1379          * #cellname:volumename or %cellname:volumename.
1380          */
1381         if (get_afs_mountpoint(pathtocheck, mountpoint, sizeof(mountpoint))) {
1382             /* skip over the '#' or '%' */
1383             cell = mountpoint + 1;
1384             /* Add this (cell:volumename) to the list of zsubs */
1385             if (zsubs)
1386                 ll_string(&zsublist, ll_s_add, cell);
1387             if (zsubs || hosts)
1388                 add_hosts(pathtocheck);
1389             if ((endofcell = strchr(mountpoint, VOLMARKER))) {
1390                 *endofcell = '\0';
1391                 if ((auth_status = auth_to_cell(context, cell, NULL, NULL))) {
1392                     if (status == AKLOG_SUCCESS)
1393                         status = auth_status;
1394                     else if (status != auth_status)
1395                         status = AKLOG_SOMETHINGSWRONG;
1396                 }
1397             }
1398         }
1399         else {
1400             if (isdir(pathtocheck, &isdirectory) < 0) {
1401                 /*
1402                  * If we've logged and still can't stat, there's
1403                  * a problem...
1404                  */
1405                 fprintf(stderr, "%s: stat(%s): %s\n", progname,
1406                         pathtocheck, strerror(errno));
1407                 return(AKLOG_BADPATH);
1408             }
1409             else if (! isdirectory) {
1410                 /* Allow only directories */
1411                 fprintf(stderr, "%s: %s: %s\n", progname, pathtocheck,
1412                         strerror(ENOTDIR));
1413                 return(AKLOG_BADPATH);
1414             }
1415         }
1416     }
1417
1418
1419     return(status);
1420 }
1421
1422
1423 /* Print usage message and exit */
1424 static void
1425 usage(void)
1426 {
1427     fprintf(stderr, "\nUsage: %s %s%s%s\n", progname,
1428             "[-d] [[-cell | -c] cell [-k krb_realm]] ",
1429             "[[-p | -path] pathname]\n",
1430             "    [-zsubs] [-hosts] [-noauth] [-noprdb] [-force] [-setpag] \n"
1431                 "    [-linked]"
1432 #ifndef HAVE_NO_KRB5_524
1433                 " [-524]"
1434 #endif
1435                 "\n");
1436     fprintf(stderr, "    -d gives debugging information.\n");
1437     fprintf(stderr, "    krb_realm is the kerberos realm of a cell.\n");
1438     fprintf(stderr, "    pathname is the name of a directory to which ");
1439     fprintf(stderr, "you wish to authenticate.\n");
1440     fprintf(stderr, "    -zsubs gives zephyr subscription information.\n");
1441     fprintf(stderr, "    -hosts gives host address information.\n");
1442     fprintf(stderr, "    -noauth does not attempt to get tokens.\n");
1443     fprintf(stderr, "    -noprdb means don't try to determine AFS ID.\n");
1444     fprintf(stderr, "    -force means replace identical tickets. \n");
1445     fprintf(stderr, "    -linked means if AFS node is linked, try both. \n");
1446     fprintf(stderr, "    -setpag set the AFS process authentication group.\n");
1447 #ifndef HAVE_NO_KRB5_524
1448     fprintf(stderr, "    -524 means use the 524 converter instead of V5 directly\n");
1449 #endif
1450     fprintf(stderr, "    No commandline arguments means ");
1451     fprintf(stderr, "authenticate to the local cell.\n");
1452     fprintf(stderr, "\n");
1453     exit(AKLOG_USAGE);
1454 }
1455
1456 int
1457 main(int argc, char *argv[])
1458 {
1459     krb5_context context;
1460     int status = AKLOG_SUCCESS;
1461     int i;
1462     int somethingswrong = FALSE;
1463
1464     cellinfo_t cellinfo;
1465
1466     extern char *progname;      /* Name of this program */
1467
1468     int cmode = FALSE;          /* Cellname mode */
1469     int pmode = FALSE;          /* Path name mode */
1470
1471     char realm[REALM_SZ];       /* Kerberos realm of afs server */
1472     char cell[BUFSIZ];          /* Cell to which we are authenticating */
1473     char path[MAXPATHLEN + 1];          /* Path length for path mode */
1474
1475     linked_list cells;          /* List of cells to log to */
1476     linked_list paths;          /* List of paths to log to */
1477     ll_node *cur_node;
1478     char *linkedcell;
1479
1480     memset(&cellinfo, 0, sizeof(cellinfo));
1481
1482     memset(realm, 0, sizeof(realm));
1483     memset(cell, 0, sizeof(cell));
1484     memset(path, 0, sizeof(path));
1485
1486     ll_init(&cells);
1487     ll_init(&paths);
1488
1489     ll_init(&zsublist);
1490     ll_init(&hostlist);
1491
1492     /* Store the program name here for error messages */
1493     if ((progname = strrchr(argv[0], DIR)))
1494         progname++;
1495     else
1496         progname = argv[0];
1497
1498     krb5_init_context(&context);
1499     initialize_KTC_error_table ();
1500     initialize_U_error_table();
1501     initialize_RXK_error_table();
1502     initialize_ACFG_error_table();
1503     initialize_PT_error_table();
1504     afs_set_com_err_hook(redirect_errors);
1505
1506     /*
1507      * Enable DES enctypes, which are currently still required for AFS.
1508      * krb5_allow_weak_crypto is MIT Kerberos 1.8.  krb5_enctype_enable is
1509      * Heimdal.
1510      */
1511 #if defined(HAVE_KRB5_ENCTYPE_ENABLE)
1512     i = krb5_enctype_valid(context, ETYPE_DES_CBC_CRC);
1513     if (i)
1514         krb5_enctype_enable(context, ETYPE_DES_CBC_CRC);
1515 #elif defined(HAVE_KRB5_ALLOW_WEAK_CRYPTO)
1516     krb5_allow_weak_crypto(context, 1);
1517 #endif
1518
1519     /* Initialize list of cells to which we have authenticated */
1520     ll_init(&authedcells);
1521
1522     /* Parse commandline arguments and make list of what to do. */
1523     for (i = 1; i < argc; i++) {
1524         if (strcmp(argv[i], "-d") == 0)
1525             dflag++;
1526         else if (strcmp(argv[i], "-noauth") == 0)
1527             noauth++;
1528         else if (strcmp(argv[i], "-zsubs") == 0)
1529             zsubs++;
1530         else if (strcmp(argv[i], "-hosts") == 0)
1531             hosts++;
1532         else if (strcmp(argv[i], "-noprdb") == 0)
1533             noprdb++;
1534         else if (strcmp(argv[i], "-linked") == 0)
1535                 linked++;
1536         else if (strcmp(argv[i], "-force") == 0)
1537             force++;
1538 #ifndef HAVE_NO_KRB5_524
1539         else if (strcmp(argv[i], "-524") == 0)
1540             do524++;
1541 #endif
1542     else if (strcmp(argv[i], "-setpag") == 0)
1543             afssetpag++;
1544         else if (((strcmp(argv[i], "-cell") == 0) ||
1545                   (strcmp(argv[i], "-c") == 0)) && !pmode)
1546             if (++i < argc) {
1547                 cmode++;
1548                 strcpy(cell, argv[i]);
1549             }
1550             else
1551                 usage();
1552         else if ((strcmp(argv[i], "-keytab") == 0))
1553             if (++i < argc) {
1554                 keytab = argv[i];
1555             }
1556             else
1557                 usage();
1558         else if ((strcmp(argv[i], "-principal") == 0))
1559             if (++i < argc) {
1560                 client = argv[i];
1561             }
1562             else
1563                 usage();
1564         else if (((strcmp(argv[i], "-path") == 0) ||
1565                   (strcmp(argv[i], "-p") == 0)) && !cmode)
1566             if (++i < argc) {
1567                 pmode++;
1568                 strcpy(path, argv[i]);
1569             }
1570             else
1571                 usage();
1572
1573         else if (argv[i][0] == '-')
1574             usage();
1575         else if (!pmode && !cmode) {
1576             if (strchr(argv[i], DIR) || (strcmp(argv[i], ".") == 0) ||
1577                 (strcmp(argv[i], "..") == 0)) {
1578                 pmode++;
1579                 strcpy(path, argv[i]);
1580             }
1581             else {
1582                 cmode++;
1583                 strcpy(cell, argv[i]);
1584             }
1585         }
1586         else
1587             usage();
1588
1589         if (cmode) {
1590             if (((i + 1) < argc) && (strcmp(argv[i + 1], "-k") == 0)) {
1591                 i+=2;
1592                 if (i < argc)
1593                     strcpy(realm, argv[i]);
1594                 else
1595                     usage();
1596             }
1597             /* Add this cell to list of cells */
1598             strcpy(cellinfo.cell, cell);
1599             strcpy(cellinfo.realm, realm);
1600             if ((cur_node = ll_add_node(&cells, ll_tail))) {
1601                 char *new_cellinfo;
1602                 if ((new_cellinfo = copy_cellinfo(&cellinfo)))
1603                     ll_add_data(cur_node, new_cellinfo);
1604                 else {
1605                     fprintf(stderr,
1606                             "%s: failure copying cellinfo.\n", progname);
1607                     exit(AKLOG_MISC);
1608                 }
1609             }
1610             else {
1611                 fprintf(stderr, "%s: failure adding cell to cells list.\n",
1612                         progname);
1613                 exit(AKLOG_MISC);
1614             }
1615             memset(&cellinfo, 0, sizeof(cellinfo));
1616             cmode = FALSE;
1617             memset(cell, 0, sizeof(cell));
1618             memset(realm, 0, sizeof(realm));
1619         }
1620         else if (pmode) {
1621             /* Add this path to list of paths */
1622             if ((cur_node = ll_add_node(&paths, ll_tail))) {
1623                 char *new_path;
1624                 if ((new_path = strdup(path)))
1625                     ll_add_data(cur_node, new_path);
1626                 else {
1627                     fprintf(stderr, "%s: failure copying path name.\n",
1628                             progname);
1629                     exit(AKLOG_MISC);
1630                 }
1631             }
1632             else {
1633                 fprintf(stderr, "%s: failure adding path to paths list.\n",
1634                         progname);
1635                 exit(AKLOG_MISC);
1636             }
1637             pmode = FALSE;
1638             memset(path, 0, sizeof(path));
1639         }
1640     }
1641
1642     /* If nothing was given, log to the local cell. */
1643     if ((cells.nelements + paths.nelements) == 0) {
1644         struct passwd *pwd;
1645
1646         status = auth_to_cell(context, NULL, NULL, &linkedcell);
1647
1648         /* If this cell is linked to a DCE cell, and user requested -linked,
1649          * get tokens for both. This is very useful when the AFS cell is
1650          * linked to a DFS cell and this system does not also have DFS.
1651          */
1652
1653         if (!status && linked && linkedcell != NULL) {
1654             afs_dprintf("Linked cell: %s\n", linkedcell);
1655             status = auth_to_cell(context, linkedcell, NULL, NULL);
1656         }
1657         if (linkedcell) {
1658             free(linkedcell);
1659             linkedcell = NULL;
1660         }
1661
1662         /*
1663          * Local hack - if the person has a file in their home
1664          * directory called ".xlog", read that for a list of
1665          * extra cells to authenticate to
1666          */
1667
1668         if ((pwd = getpwuid(getuid())) != NULL) {
1669             struct stat sbuf;
1670             FILE *f;
1671             char fcell[100], xlog_path[512];
1672
1673             strcpy(xlog_path, pwd->pw_dir);
1674             strcat(xlog_path, "/.xlog");
1675
1676             if ((stat(xlog_path, &sbuf) == 0) &&
1677                 ((f = fopen(xlog_path, "r")) != NULL)) {
1678
1679                 afs_dprintf("Reading %s for cells to authenticate to.\n",
1680                         xlog_path);
1681
1682                 while (fgets(fcell, 100, f) != NULL) {
1683                     int auth_status;
1684
1685                     fcell[strlen(fcell) - 1] = '\0';
1686
1687                     afs_dprintf("Found cell %s in %s.\n", fcell, xlog_path);
1688
1689                     auth_status = auth_to_cell(context, fcell, NULL, NULL);
1690                     if (status == AKLOG_SUCCESS)
1691                         status = auth_status;
1692                     else
1693                         status = AKLOG_SOMETHINGSWRONG;
1694                 }
1695             }
1696         }
1697     }
1698     else {
1699         /* Log to all cells in the cells list first */
1700         for (cur_node = cells.first; cur_node; cur_node = cur_node->next) {
1701             memcpy((char *)&cellinfo, cur_node->data, sizeof(cellinfo));
1702             if ((status = auth_to_cell(context, cellinfo.cell, cellinfo.realm,
1703                                        &linkedcell)))
1704                 somethingswrong++;
1705             else {
1706                 if (linked && linkedcell != NULL) {
1707                     afs_dprintf("Linked cell: %s\n", linkedcell);
1708                     if ((status = auth_to_cell(context, linkedcell,
1709                                                cellinfo.realm, NULL)))
1710                         somethingswrong++;
1711                 }
1712                 if (linkedcell != NULL) {
1713                     free(linkedcell);
1714                     linkedcell = NULL;
1715                 }
1716             }
1717         }
1718
1719         /* Then, log to all paths in the paths list */
1720         for (cur_node = paths.first; cur_node; cur_node = cur_node->next) {
1721             if ((status = auth_to_path(context, cur_node->data)))
1722                 somethingswrong++;
1723         }
1724
1725         /*
1726          * If only one thing was logged to, we'll return the status
1727          * of the single call.  Otherwise, we'll return a generic
1728          * something failed status.
1729          */
1730         if (somethingswrong && ((cells.nelements + paths.nelements) > 1))
1731             status = AKLOG_SOMETHINGSWRONG;
1732     }
1733
1734     /* If we are keeping track of zephyr subscriptions, print them. */
1735     if (zsubs)
1736         for (cur_node = zsublist.first; cur_node; cur_node = cur_node->next) {
1737             printf("zsub: %s\n", cur_node->data);
1738         }
1739
1740     /* If we are keeping track of host information, print it. */
1741     if (hosts)
1742         for (cur_node = hostlist.first; cur_node; cur_node = cur_node->next) {
1743             printf("host: %s\n", cur_node->data);
1744         }
1745
1746     exit(status);
1747 }
1748
1749 static int
1750 isdir(char *path, unsigned char *val)
1751 {
1752     struct stat statbuf;
1753
1754     if (lstat(path, &statbuf) < 0)
1755         return (-1);
1756     else {
1757         if ((statbuf.st_mode & S_IFMT) == S_IFDIR)
1758             *val = TRUE;
1759         else
1760             *val = FALSE;
1761         return (0);
1762     }
1763 }
1764
1765 static krb5_error_code
1766 get_credv5_akimpersonate(krb5_context context,
1767                          char* keytab,
1768                          krb5_principal service_principal,
1769                          krb5_principal client_principal,
1770                          time_t starttime,
1771                          time_t endtime,
1772                          int *allowed_enctypes,
1773                          int *paddress,
1774                          krb5_creds** out_creds /* out */ )
1775 {
1776 #if defined(USING_HEIMDAL) || (defined(HAVE_ENCODE_KRB5_ENC_TKT) && defined(HAVE_ENCODE_KRB5_TICKET) && defined(HAVE_KRB5_C_ENCRYPT))
1777     krb5_error_code code;
1778     krb5_keytab kt = 0;
1779     krb5_kt_cursor cursor[1];
1780     krb5_keytab_entry entry[1];
1781     krb5_ccache cc = 0;
1782     krb5_creds *creds = 0;
1783     krb5_enctype enctype;
1784     krb5_kvno kvno;
1785     krb5_keyblock session_key[1];
1786 #if USING_HEIMDAL
1787     Ticket ticket_reply[1];
1788     EncTicketPart enc_tkt_reply[1];
1789     krb5_address address[30];
1790     krb5_addresses faddr[1];
1791     int temp_vno[1];
1792     time_t temp_time[2];
1793 #else
1794     krb5_ticket ticket_reply[1];
1795     krb5_enc_tkt_part enc_tkt_reply[1];
1796     krb5_address address[30], *faddr[30];
1797     krb5_data * temp;
1798 #endif
1799     int i;
1800     static int any_enctype[] = {0};
1801     *out_creds = 0;
1802     if (!(creds = malloc(sizeof *creds))) {
1803         code = ENOMEM;
1804         goto cleanup;
1805     }
1806     if (!allowed_enctypes)
1807         allowed_enctypes = any_enctype;
1808
1809     cc = 0;
1810     enctype = 0; /* AKIMPERSONATE_IGNORE_ENCTYPE */
1811     kvno = 0; /* AKIMPERSONATE_IGNORE_VNO */
1812     memset((char*)creds, 0, sizeof *creds);
1813     memset((char*)entry, 0, sizeof *entry);
1814     memset((char*)session_key, 0, sizeof *session_key);
1815     memset((char*)ticket_reply, 0, sizeof *ticket_reply);
1816     memset((char*)enc_tkt_reply, 0, sizeof *enc_tkt_reply);
1817     code = krb5_kt_resolve(context, keytab, &kt);
1818     if (code) {
1819         if (keytab)
1820             afs_com_err(progname, code, "while resolving keytab %s", keytab);
1821         else
1822             afs_com_err(progname, code, "while resolving default keytab");
1823         goto cleanup;
1824     }
1825
1826     if (service_principal) {
1827         for (i = 0; (enctype = allowed_enctypes[i]) || !i; ++i) {
1828             code = krb5_kt_get_entry(context,
1829                                      kt,
1830                                      service_principal,
1831                                      kvno,
1832                                      enctype,
1833                                      entry);
1834             if (!code) {
1835                 if (allowed_enctypes[i])
1836                     deref_keyblock_enctype(session_key) = allowed_enctypes[i];
1837                 break;
1838             }
1839         }
1840         if (code) {
1841             afs_com_err(progname, code,"while scanning keytab entries");
1842             goto cleanup;
1843         }
1844     } else {
1845         krb5_keytab_entry new[1];
1846         int best = -1;
1847         memset(new, 0, sizeof *new);
1848         if ((code == krb5_kt_start_seq_get(context, kt, cursor))) {
1849             afs_com_err(progname, code, "while starting keytab scan");
1850             goto cleanup;
1851         }
1852         while (!(code = krb5_kt_next_entry(context, kt, new, cursor))) {
1853             for (i = 0;
1854                     allowed_enctypes[i] && allowed_enctypes[i]
1855                      != deref_entry_enctype(new); ++i)
1856                 ;
1857             if ((!i || allowed_enctypes[i]) &&
1858                 (best < 0 || best > i)) {
1859                 krb5_free_keytab_entry_contents(context, entry);
1860                 *entry = *new;
1861                 memset(new, 0, sizeof *new);
1862             } else krb5_free_keytab_entry_contents(context, new);
1863         }
1864         if ((i = krb5_kt_end_seq_get(context, kt, cursor))) {
1865             afs_com_err(progname, i, "while ending keytab scan");
1866             code = i;
1867             goto cleanup;
1868         }
1869         if (best < 0) {
1870             afs_com_err(progname, code, "while scanning keytab");
1871             goto cleanup;
1872         }
1873         deref_keyblock_enctype(session_key) = deref_entry_enctype(entry);
1874     }
1875
1876     /* Make Ticket */
1877
1878 #if USING_HEIMDAL
1879     if ((code = krb5_generate_random_keyblock(context,
1880                                               deref_keyblock_enctype(session_key), session_key))) {
1881         afs_com_err(progname, code, "while making session key");
1882         goto cleanup;
1883     }
1884     enc_tkt_reply->flags.initial = 1;
1885     enc_tkt_reply->transited.tr_type = DOMAIN_X500_COMPRESS;
1886     enc_tkt_reply->cname = client_principal->name;
1887     enc_tkt_reply->crealm = client_principal->realm;
1888     enc_tkt_reply->key = *session_key;
1889     {
1890         static krb5_data empty_string;
1891         enc_tkt_reply->transited.contents = empty_string;
1892     }
1893     enc_tkt_reply->authtime = starttime;
1894     enc_tkt_reply->starttime = temp_time;
1895     *enc_tkt_reply->starttime = starttime;
1896 #if 0
1897     enc_tkt_reply->renew_till = temp_time + 1;
1898     *enc_tkt_reply->renew_till = endtime;
1899 #endif
1900     enc_tkt_reply->endtime = endtime;
1901 #else
1902     if ((code = krb5_c_make_random_key(context,
1903                                        deref_keyblock_enctype(session_key), session_key))) {
1904         afs_com_err(progname, code, "while making session key");
1905         goto cleanup;
1906     }
1907     enc_tkt_reply->magic = KV5M_ENC_TKT_PART;
1908 #define DATACAST        (unsigned char *)
1909     enc_tkt_reply->flags |= TKT_FLG_INITIAL;
1910     enc_tkt_reply->transited.tr_type = KRB5_DOMAIN_X500_COMPRESS;
1911     enc_tkt_reply->session = session_key;
1912     enc_tkt_reply->client = client_principal;
1913     {
1914         static krb5_data empty_string;
1915         enc_tkt_reply->transited.tr_contents = empty_string;
1916     }
1917     enc_tkt_reply->times.authtime = starttime;
1918     enc_tkt_reply->times.starttime = starttime; /* krb524init needs this */
1919     enc_tkt_reply->times.endtime = endtime;
1920 #endif  /* USING_HEIMDAL */
1921     /* NB:  We will discard address for now--ignoring caddr field
1922        in any case.  MIT branch does what it always did. */
1923
1924     if (paddress && *paddress) {
1925         deref_enc_tkt_addrs(enc_tkt_reply) = faddr;
1926 #if USING_HEIMDAL
1927         faddr->len = 0;
1928         faddr->val = address;
1929 #endif
1930         for (i = 0; paddress[i]; ++i) {
1931 #if USING_HEIMDAL
1932             address[i].addr_type = KRB5_ADDRESS_INET;
1933             address[i].address.data = (void*)(paddress+i);
1934             address[i].address.length = sizeof(paddress[i]);
1935 #else
1936 #if !USING_SSL
1937             address[i].magic = KV5M_ADDRESS;
1938             address[i].addrtype = ADDRTYPE_INET;
1939 #else
1940             address[i].addrtype = AF_INET;
1941 #endif
1942             address[i].contents = (void*)(paddress+i);
1943             address[i].length = sizeof(int);
1944             faddr[i] = address+i;
1945 #endif
1946         }
1947 #if USING_HEIMDAL
1948         faddr->len = i;
1949 #else
1950         faddr[i] = 0;
1951 #endif
1952     }
1953
1954 #if USING_HEIMDAL
1955     ticket_reply->sname = service_principal->name;
1956     ticket_reply->realm = service_principal->realm;
1957
1958     { /* crypto block */
1959         krb5_crypto crypto = 0;
1960         unsigned char *buf = 0;
1961         size_t buf_size, buf_len;
1962         char *what;
1963
1964         ASN1_MALLOC_ENCODE(EncTicketPart, buf, buf_size,
1965                            enc_tkt_reply, &buf_len, code);
1966         if(code) {
1967             afs_com_err(progname, code, "while encoding ticket");
1968             goto cleanup;
1969         }
1970
1971         if(buf_len != buf_size) {
1972             afs_com_err(progname, code,
1973                     "%u != %u while encoding ticket (internal ASN.1 encoder error",
1974                     (unsigned int)buf_len, (unsigned int)buf_size);
1975             goto cleanup;
1976         }
1977         what = "krb5_crypto_init";
1978         code = krb5_crypto_init(context,
1979                                 &deref_entry_keyblock(entry),
1980                                 deref_entry_enctype(entry),
1981                                 &crypto);
1982         if(!code) {
1983             what = "krb5_encrypt";
1984             code = krb5_encrypt_EncryptedData(context, crypto, KRB5_KU_TICKET,
1985                                               buf, buf_len, entry->vno, &(ticket_reply->enc_part));
1986         }
1987         if (buf) free(buf);
1988         if (crypto) krb5_crypto_destroy(context, crypto);
1989         if(code) {
1990             afs_com_err(progname, code, "while %s", what);
1991             goto cleanup;
1992         }
1993     } /* crypto block */
1994     ticket_reply->enc_part.etype = deref_entry_enctype(entry);
1995     ticket_reply->enc_part.kvno = temp_vno;
1996     *ticket_reply->enc_part.kvno = entry->vno;
1997     ticket_reply->tkt_vno = 5;
1998 #else
1999     ticket_reply->server = service_principal;
2000     ticket_reply->enc_part2 = enc_tkt_reply;
2001     if ((code = krb5_encrypt_tkt_part(context, &deref_entry_keyblock(entry), ticket_reply))) {
2002         afs_com_err(progname, code, "while making ticket");
2003         goto cleanup;
2004     }
2005     ticket_reply->enc_part.kvno = entry->vno;
2006 #endif
2007
2008     /* Construct Creds */
2009
2010     if ((code = krb5_copy_principal(context, service_principal,
2011                                     &creds->server))) {
2012         afs_com_err(progname, code, "while copying service principal");
2013         goto cleanup;
2014     }
2015     if ((code = krb5_copy_principal(context, client_principal,
2016                                     &creds->client))) {
2017         afs_com_err(progname, code, "while copying client principal");
2018         goto cleanup;
2019     }
2020     if ((code = krb5_copy_keyblock_contents(context, session_key,
2021                                             &deref_session_key(creds)))) {
2022         afs_com_err(progname, code, "while copying session key");
2023         goto cleanup;
2024     }
2025
2026 #if USING_HEIMDAL
2027     creds->times.authtime = enc_tkt_reply->authtime;
2028     creds->times.starttime = *(enc_tkt_reply->starttime);
2029     creds->times.endtime = enc_tkt_reply->endtime;
2030     creds->times.renew_till = 0; /* *(enc_tkt_reply->renew_till) */
2031     creds->flags.b = enc_tkt_reply->flags;
2032 #else
2033     creds->times = enc_tkt_reply->times;
2034     creds->ticket_flags = enc_tkt_reply->flags;
2035 #endif
2036     if (!deref_enc_tkt_addrs(enc_tkt_reply))
2037         ;
2038     else if ((code = krb5_copy_addresses(context,
2039                                          deref_enc_tkt_addrs(enc_tkt_reply), &creds->addresses))) {
2040         afs_com_err(progname, code, "while copying addresses");
2041         goto cleanup;
2042     }
2043
2044 #if USING_HEIMDAL
2045     {
2046         size_t creds_tkt_len;
2047         ASN1_MALLOC_ENCODE(Ticket, creds->ticket.data, creds->ticket.length,
2048                            ticket_reply, &creds_tkt_len, code);
2049         if(code) {
2050             afs_com_err(progname, code, "while encoding ticket");
2051             goto cleanup;
2052         }
2053     }
2054 #else
2055     if ((code = encode_krb5_ticket(ticket_reply, &temp))) {
2056         afs_com_err(progname, code, "while encoding ticket");
2057         goto cleanup;
2058     }
2059     creds->ticket = *temp;
2060     free(temp);
2061 #endif
2062     /* return creds */
2063     *out_creds = creds;
2064     creds = 0;
2065 cleanup:
2066     if (deref_enc_data(&ticket_reply->enc_part))
2067         free(deref_enc_data(&ticket_reply->enc_part));
2068     krb5_free_keytab_entry_contents(context, entry);
2069     if (client_principal)
2070         krb5_free_principal(context, client_principal);
2071     if (service_principal)
2072         krb5_free_principal(context, service_principal);
2073     if (cc)
2074         krb5_cc_close(context, cc);
2075     if (kt)
2076         krb5_kt_close(context, kt);
2077     if (creds) krb5_free_creds(context, creds);
2078     krb5_free_keyblock_contents(context, session_key);
2079     return code;
2080 #else
2081     return -1;
2082 #endif
2083 }
2084
2085
2086 static krb5_error_code
2087 get_credv5(krb5_context context, char *name, char *inst, char *realm,
2088            krb5_creds **creds)
2089 {
2090     krb5_creds increds;
2091     krb5_error_code r;
2092     static krb5_principal client_principal = 0;
2093
2094     afs_dprintf("Getting tickets: %s%s%s@%s\n", name,
2095             (inst && inst[0]) ? "/" : "", inst ? inst : "", realm);
2096
2097     memset(&increds, 0, sizeof(increds));
2098 /* ANL - instance may be ptr to a null string. Pass null then */
2099     if ((r = krb5_build_principal(context, &increds.server,
2100                                   strlen(realm), realm,
2101                                   name,
2102                                   (inst && strlen(inst)) ? inst : (void *) NULL,
2103                                   (void *) NULL))) {
2104         return r;
2105     }
2106
2107
2108     if (!_krb425_ccache) {
2109         r = krb5_cc_default(context, &_krb425_ccache);
2110         if (r)
2111             return r;
2112     }
2113     if (!client_principal) {
2114         if (client) {
2115             r = krb5_parse_name(context, client,  &client_principal);
2116         } else {
2117             r = krb5_cc_get_principal(context, _krb425_ccache, &client_principal);
2118         }
2119         if (r)
2120             return r;
2121     }
2122
2123     increds.client = client_principal;
2124     increds.times.endtime = 0;
2125     /* Ask for DES since that is what V4 understands */
2126     get_creds_enctype((&increds)) = ENCTYPE_DES_CBC_CRC;
2127
2128     if (keytab) {
2129         int allowed_enctypes[] = {
2130             ENCTYPE_DES_CBC_CRC, 0
2131         };
2132
2133         r = get_credv5_akimpersonate(context,
2134                                      keytab,
2135                                      increds.server,
2136                                      increds.client,
2137                                      300, ((~0U)>>1),
2138                                      allowed_enctypes,
2139                                      0 /* paddress */,
2140                                      creds /* out */);
2141     } else {
2142         r = krb5_get_credentials(context, 0, _krb425_ccache, &increds, creds);
2143     }
2144     return r;
2145 }
2146
2147
2148 static int
2149 get_user_realm(krb5_context context, char **realm)
2150 {
2151     static krb5_principal client_principal = 0;
2152     krb5_error_code r = 0;
2153
2154     *realm = NULL;
2155
2156     if (!_krb425_ccache)
2157         krb5_cc_default(context, &_krb425_ccache);
2158     if (!client_principal) {
2159         if (client) {
2160             r = krb5_parse_name(context, client,  &client_principal);
2161         } else {
2162             r = krb5_cc_get_principal(context, _krb425_ccache, &client_principal);
2163         }
2164         if (r)
2165             return r;
2166     }
2167
2168     *realm = extract_realm(context, client_principal);
2169     if (*realm == NULL)
2170         return ENOMEM;
2171
2172     return(r);
2173 }