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