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