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