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