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