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