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