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