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