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