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