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