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