aklog: heimdal kvno is rapidly changing
[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     size_t len;
845
846     *token = NULL;
847     *authuser = NULL;
848     *foreign = 0;
849
850     status = rxkad_get_ticket(context, realm, cell, &v5cred, &realmUsed);
851     if (status)
852         return status;
853
854     if (do524)
855         status = rxkad_get_converted_token(context, v5cred, token, &username);
856     else
857         status = rxkad_build_native_token(context, v5cred, token, &username);
858
859     if (status)
860         goto out;
861
862     /* We now have the username, plus the realm name, so stitch them together
863      * to give us the name that the ptserver will know the user by */
864     if (realmUsed == NULL) {
865         *authuser = username;
866         username = NULL;
867         *foreign = 0;
868     } else {
869         len = strlen(username)+strlen(realmUsed)+2;
870         *authuser = malloc(len);
871         snprintf(*authuser, len, "%s@%s", username, realmUsed);
872         *foreign = 1;
873     }
874
875 out:
876     if (realmUsed)
877         free(realmUsed);
878     if (username)
879         free(username);
880
881     return status;
882 }
883
884 /* 
885  * Log to a cell.  If the cell has already been logged to, return without
886  * doing anything.  Otherwise, log to it and mark that it has been logged
887  * to.
888  */
889 static int
890 auth_to_cell(krb5_context context, const char *config, 
891              char *cell, char *realm, char **linkedcell)
892 {
893     int status = AKLOG_SUCCESS;
894     int isForeign = 0;
895     char *username = NULL;      /* To hold client username structure */
896     afs_int32 viceId;           /* AFS uid of user */
897
898     char *local_cell = NULL;
899     struct ktc_tokenUnion *rxkadToken = NULL;
900     struct ktc_setTokenData *token;
901     struct ktc_setTokenData *btoken = NULL;
902     struct afsconf_cell cellconf;
903
904     /* NULL or empty cell returns information on local cell */
905     if ((status = get_cellconfig(config, cell, &cellconf, &local_cell)))
906         return(status);
907
908     if (linkedcell != NULL) {
909         if (cellconf.linkedCell != NULL) {
910             *linkedcell = strdup(cellconf.linkedCell);
911             if (*linkedcell == NULL) {
912                 status = ENOMEM;
913                 goto out;
914             }
915         } else {
916             *linkedcell = NULL;
917         }
918     }
919
920     if (ll_string(&authedcells, ll_s_check, cellconf.name)) {
921         afs_dprintf("Already authenticated to %s (or tried to)\n", cellconf.name);
922         status = AKLOG_SUCCESS;
923         goto out;
924     }
925
926     /*
927      * Record that we have attempted to log to this cell.  We do this
928      * before we try rather than after so that we will not try
929      * and fail repeatedly for one cell.
930      */
931     ll_string(&authedcells, ll_s_add, cellconf.name);
932
933     /*
934      * Record this cell in the list of zephyr subscriptions.  We may
935      * want zephyr subscriptions even if authentication fails.
936      * If this is done after we attempt to get tokens, aklog -zsubs
937      * can return something different depending on whether or not we
938      * are in -noauth mode.
939      */
940     if (ll_string(&zsublist, ll_s_add, cellconf.name) == LL_FAILURE) {
941         fprintf(stderr,
942                 "%s: failure adding cell %s to zephyr subscriptions list.\n",
943                 progname, cellconf.name);
944         exit(AKLOG_MISC);
945     }
946     if (ll_string(&zsublist, ll_s_add, local_cell) == LL_FAILURE) {
947         fprintf(stderr,
948                 "%s: failure adding cell %s to zephyr subscriptions list.\n",
949                 progname, local_cell);
950         exit(AKLOG_MISC);
951     }
952
953     if (!noauth) {
954         afs_dprintf("Authenticating to cell %s (server %s).\n", cellconf.name,
955                 cellconf.hostName[0]);
956
957         token = token_buildTokenJar(cellconf.name);
958         if (token == NULL) {
959             status = ENOMEM;
960             goto out;
961         }
962
963         status = rxkad_get_token(context, &cellconf, realm, &rxkadToken,
964                                  &username, &isForeign);
965         if (status)
966             goto out;
967
968         /* We need to keep the token structure around so that we can stick
969          * the viceId into it (once we know it) */
970         status = token_addToken(token, rxkadToken);
971         if (status) {
972             afs_dprintf("Add Token failed with %d", status);
973             goto out;
974         }
975
976         if (!force &&
977             ktc_GetTokenEx(cellconf.name, &btoken) == 0 &&
978             token_SetsEquivalent(token, btoken)) {
979
980             token_FreeSet(&btoken);
981             afs_dprintf("Identical tokens already exist; skipping.\n");
982             status = AKLOG_SUCCESS;
983             goto out;
984         }
985
986         if (btoken)
987             token_FreeSet(&btoken);
988
989 #ifdef FORCE_NOPRDB
990         noprdb = 1;
991 #endif
992
993         if (noprdb) {
994             afs_dprintf("Not resolving name %s to id (-noprdb set)\n", username);
995         }
996         else {
997             afs_dprintf("About to resolve name %s to id in cell %s.\n", username,
998                     cellconf.name);
999
1000             if (!pr_Initialize (0,  AFSDIR_CLIENT_ETC_DIRPATH, cellconf.name))
1001                 status = pr_SNameToId (username, &viceId);
1002
1003             if (status)
1004                 afs_dprintf("Error %d\n", status);
1005             else
1006                 afs_dprintf("Id %d\n", (int) viceId);
1007
1008
1009             /*
1010              * This code is taken from cklog -- it lets people
1011              * automatically register with the ptserver in foreign cells
1012              */
1013
1014 #ifdef ALLOW_REGISTER
1015             if ((status == 0) && (viceId == ANONYMOUSID) && isForeign) {
1016                 afs_dprintf("doing first-time registration of %s at %s\n",
1017                         username, cellconf.name);
1018                 viceId = 0;
1019
1020                 status = ktc_SetTokenEx(token);
1021                 if (status) {
1022                     afs_com_err(progname, status,
1023                                 "while obtaining tokens for cell %s",
1024                                 cellconf.name);
1025                     status = AKLOG_TOKEN;
1026                 }
1027
1028                 /*
1029                  * In case you're wondering, we don't need to change the
1030                  * filename here because we're still connecting to the
1031                  * same cell -- we're just using a different authenticat ion
1032                  * level
1033                  */
1034
1035                 if ((status = pr_Initialize(1L,  AFSDIR_CLIENT_ETC_DIRPATH,
1036                                             cellconf.name))) {
1037                     printf("Error %d\n", status);
1038                 }
1039
1040                 if ((status = pr_CreateUser(username, &viceId))) {
1041                     fprintf(stderr, "%s: %s so unable to create remote PTS "
1042                             "user %s in cell %s (status: %d).\n", progname,
1043                             afs_error_message(status), username, cellconf.name,
1044                             status);
1045                     viceId = ANONYMOUSID;
1046                 } else {
1047                     printf("created cross-cell entry for %s (Id %d) at %s\n",
1048                            username, viceId, cellconf.name);
1049                 }
1050             }
1051 #endif /* ALLOW_REGISTER */
1052
1053             if ((status == 0) && (viceId != ANONYMOUSID)) {
1054                 status = token_setRxkadViceId(rxkadToken, viceId);
1055                 if (status) {
1056                     fprintf(stderr, "Error %d setting rxkad ViceId\n", status);
1057                     status = AKLOG_SUCCESS;
1058                 } else {
1059                     token_replaceToken(token, rxkadToken);
1060                 }
1061             }
1062         }
1063
1064         afs_dprintf("Setting tokens. %s @ %s \n", username, cellconf.name);
1065
1066 #ifndef AFS_AIX51_ENV
1067         /* on AIX 4.1.4 with AFS 3.4a+ if a write is not done before
1068          * this routine, it will not add the token. It is not clear what
1069          * is going on here! So we will do the following operation.
1070          * On AIX 5, it causes the parent program to die, so we won't.
1071          */
1072         write(2,"",0); /* dummy write */
1073 #endif
1074         token_setPag(token, afssetpag);
1075         status = ktc_SetTokenEx(token);
1076         if (status) {
1077             afs_com_err(progname, status, "while setting tokens for cell %s",
1078                         cellconf.name);
1079             status = AKLOG_TOKEN;
1080         }
1081     }
1082     else
1083         afs_dprintf("Noauth mode; not authenticating.\n");
1084
1085 out:
1086     if (rxkadToken) {
1087         token_freeToken(&rxkadToken);
1088     }
1089
1090     if (local_cell)
1091         free(local_cell);
1092     if (username)
1093         free(username);
1094
1095     return(status);
1096 }
1097
1098 static int
1099 get_afs_mountpoint(char *file, char *mountpoint, int size)
1100 {
1101 #ifdef AFS_SUN_ENV
1102     char V ='V'; /* AFS has problem on Sun with pioctl */
1103 #endif
1104     char our_file[MAXPATHLEN + 1];
1105     char *parent_dir;
1106     char *last_component;
1107     struct ViceIoctl vio;
1108     char cellname[BUFSIZ];
1109
1110     memset(our_file, 0, sizeof(our_file));
1111     strcpy(our_file, file);
1112
1113     if ((last_component = strrchr(our_file, DIR))) {
1114         *last_component++ = 0;
1115         parent_dir = our_file;
1116     }
1117     else {
1118         last_component = our_file;
1119         parent_dir = ".";
1120     }
1121
1122     memset(cellname, 0, sizeof(cellname));
1123
1124     vio.in = last_component;
1125     vio.in_size = strlen(last_component)+1;
1126     vio.out_size = size;
1127     vio.out = mountpoint;
1128
1129     if (!pioctl(parent_dir, VIOC_AFS_STAT_MT_PT, &vio, 0)) {
1130         if (strchr(mountpoint, VOLMARKER) == NULL) {
1131             vio.in = file;
1132             vio.in_size = strlen(file) + 1;
1133             vio.out_size = sizeof(cellname);
1134             vio.out = cellname;
1135
1136             if (!pioctl(file, VIOC_FILE_CELL_NAME, &vio, 1)) {
1137                 strcat(cellname, VOLMARKERSTRING);
1138                 strcat(cellname, mountpoint + 1);
1139                 memset(mountpoint + 1, 0, size - 1);
1140                 strcpy(mountpoint + 1, cellname);
1141             }
1142         }
1143         return(TRUE);
1144     }
1145     else
1146         return(FALSE);
1147 }
1148
1149 /*
1150  * This routine each time it is called returns the next directory
1151  * down a pathname.  It resolves all symbolic links.  The first time
1152  * it is called, it should be called with the name of the path
1153  * to be descended.  After that, it should be called with the arguemnt
1154  * NULL.
1155  */
1156 static char *
1157 next_path(char *origpath)
1158 {
1159     static char path[MAXPATHLEN + 1];
1160     static char pathtocheck[MAXPATHLEN + 1];
1161
1162     int link = FALSE;           /* Is this a symbolic link? */
1163     char linkbuf[MAXPATHLEN + 1];
1164     char tmpbuf[MAXPATHLEN + 1];
1165
1166     static char *last_comp;     /* last component of directory name */
1167     static char *elast_comp;    /* End of last component */
1168     char *t;
1169     int len;
1170
1171     static int symlinkcount = 0; /* We can't exceed MAXSYMLINKS */
1172
1173     /* If we are given something for origpath, we are initializing only. */
1174     if (origpath) {
1175         memset(path, 0, sizeof(path));
1176         memset(pathtocheck, 0, sizeof(pathtocheck));
1177         strcpy(path, origpath);
1178         last_comp = path;
1179         symlinkcount = 0;
1180         return(NULL);
1181     }
1182
1183     /* We were not given origpath; find then next path to check */
1184
1185     /* If we've gotten all the way through already, return NULL */
1186     if (last_comp == NULL)
1187         return(NULL);
1188
1189     do {
1190         while (*last_comp == DIR)
1191             strncat(pathtocheck, last_comp++, 1);
1192         len = (elast_comp = strchr(last_comp, DIR))
1193             ? elast_comp - last_comp : strlen(last_comp);
1194         strncat(pathtocheck, last_comp, len);
1195         memset(linkbuf, 0, sizeof(linkbuf));
1196         if ((link = (readlink(pathtocheck, linkbuf,
1197                                     sizeof(linkbuf)) > 0))) {
1198             if (++symlinkcount > MAXSYMLINKS) {
1199                 fprintf(stderr, "%s: %s\n", progname, strerror(ELOOP));
1200                 exit(AKLOG_BADPATH);
1201             }
1202             memset(tmpbuf, 0, sizeof(tmpbuf));
1203             if (elast_comp)
1204                 strcpy(tmpbuf, elast_comp);
1205             if (linkbuf[0] == DIR) {
1206                 /*
1207                  * If this is a symbolic link to an absolute path,
1208                  * replace what we have by the absolute path.
1209                  */
1210                 memset(path, 0, strlen(path));
1211                 memcpy(path, linkbuf, sizeof(linkbuf));
1212                 strcat(path, tmpbuf);
1213                 last_comp = path;
1214                 elast_comp = NULL;
1215                 memset(pathtocheck, 0, sizeof(pathtocheck));
1216             }
1217             else {
1218                 /*
1219                  * If this is a symbolic link to a relative path,
1220                  * replace only the last component with the link name.
1221                  */
1222                 strncpy(last_comp, linkbuf, strlen(linkbuf) + 1);
1223                 strcat(path, tmpbuf);
1224                 elast_comp = NULL;
1225                 if ((t = strrchr(pathtocheck, DIR))) {
1226                     t++;
1227                     memset(t, 0, strlen(t));
1228                 }
1229                 else
1230                     memset(pathtocheck, 0, sizeof(pathtocheck));
1231             }
1232         }
1233         else
1234             last_comp = elast_comp;
1235     }
1236     while(link);
1237
1238     return(pathtocheck);
1239 }
1240
1241 static void
1242 add_hosts(char *file)
1243 {
1244 #ifdef AFS_SUN_ENV
1245     char V = 'V'; /* AFS has problem on SunOS */
1246 #endif
1247     struct ViceIoctl vio;
1248     char outbuf[BUFSIZ];
1249     long *phosts;
1250     int i;
1251     struct hostent *hp;
1252     struct in_addr in;
1253
1254     memset(outbuf, 0, sizeof(outbuf));
1255
1256     vio.out_size = sizeof(outbuf);
1257     vio.in_size = 0;
1258     vio.out = outbuf;
1259
1260     afs_dprintf("Getting list of hosts for %s\n", file);
1261
1262     /* Don't worry about errors. */
1263     if (!pioctl(file, VIOCWHEREIS, &vio, 1)) {
1264         phosts = (long *) outbuf;
1265
1266         /*
1267          * Lists hosts that we care about.  If ALLHOSTS is defined,
1268          * then all hosts that you ever may possible go through are
1269          * included in this list.  If not, then only hosts that are
1270          * the only ones appear.  That is, if a volume you must use
1271          * is replaced on only one server, that server is included.
1272          * If it is replicated on many servers, then none are included.
1273          * This is not perfect, but the result is that people don't
1274          * get subscribed to a lot of instances of FILSRV that they
1275          * probably won't need which reduces the instances of
1276          * people getting messages that don't apply to them.
1277          */
1278 #ifndef ALLHOSTS
1279         if (phosts[1] != '\0')
1280             return;
1281 #endif
1282         for (i = 0; phosts[i]; i++) {
1283             if (hosts) {
1284                 in.s_addr = phosts[i];
1285                 afs_dprintf("Got host %s\n", inet_ntoa(in));
1286                 ll_string(&hostlist, ll_s_add, (char *)inet_ntoa(in));
1287             }
1288             if (zsubs && (hp=gethostbyaddr((char *) &phosts[i],sizeof(long),AF_INET))) {
1289                 afs_dprintf("Got host %s\n", hp->h_name);
1290                 ll_string(&zsublist, ll_s_add, hp->h_name);
1291             }
1292         }
1293     }
1294 }
1295
1296 /*
1297  * This routine descends through a path to a directory, logging to
1298  * every cell it encounters along the way.
1299  */
1300 static int
1301 auth_to_path(krb5_context context, const char *config, char *path)
1302 {
1303     int status = AKLOG_SUCCESS;
1304     int auth_status = AKLOG_SUCCESS;
1305
1306     char *nextpath;
1307     char pathtocheck[MAXPATHLEN + 1];
1308     char mountpoint[MAXPATHLEN + 1];
1309
1310     char *cell;
1311     char *endofcell;
1312
1313     u_char isdirectory;
1314
1315     /* Initialize */
1316     if (path[0] == DIR)
1317         strcpy(pathtocheck, path);
1318     else {
1319         if (getcwd(pathtocheck, sizeof(pathtocheck)) == NULL) {
1320             fprintf(stderr, "Unable to find current working directory:\n");
1321             fprintf(stderr, "%s\n", pathtocheck);
1322             fprintf(stderr, "Try an absolute pathname.\n");
1323             exit(AKLOG_BADPATH);
1324         }
1325         else {
1326             strcat(pathtocheck, DIRSTRING);
1327             strcat(pathtocheck, path);
1328         }
1329     }
1330     next_path(pathtocheck);
1331
1332     /* Go on to the next level down the path */
1333     while ((nextpath = next_path(NULL))) {
1334         strcpy(pathtocheck, nextpath);
1335         afs_dprintf("Checking directory %s\n", pathtocheck);
1336         /*
1337          * If this is an afs mountpoint, determine what cell from
1338          * the mountpoint name which is of the form
1339          * #cellname:volumename or %cellname:volumename.
1340          */
1341         if (get_afs_mountpoint(pathtocheck, mountpoint, sizeof(mountpoint))) {
1342             /* skip over the '#' or '%' */
1343             cell = mountpoint + 1;
1344             /* Add this (cell:volumename) to the list of zsubs */
1345             if (zsubs)
1346                 ll_string(&zsublist, ll_s_add, cell);
1347             if (zsubs || hosts)
1348                 add_hosts(pathtocheck);
1349             if ((endofcell = strchr(mountpoint, VOLMARKER))) {
1350                 *endofcell = '\0';
1351                 auth_status = auth_to_cell(context, config, cell, NULL, NULL);
1352                 if (auth_status) {
1353                     if (status == AKLOG_SUCCESS)
1354                         status = auth_status;
1355                     else if (status != auth_status)
1356                         status = AKLOG_SOMETHINGSWRONG;
1357                 }
1358             }
1359         }
1360         else {
1361             if (isdir(pathtocheck, &isdirectory) < 0) {
1362                 /*
1363                  * If we've logged and still can't stat, there's
1364                  * a problem...
1365                  */
1366                 fprintf(stderr, "%s: stat(%s): %s\n", progname,
1367                         pathtocheck, strerror(errno));
1368                 return(AKLOG_BADPATH);
1369             }
1370             else if (! isdirectory) {
1371                 /* Allow only directories */
1372                 fprintf(stderr, "%s: %s: %s\n", progname, pathtocheck,
1373                         strerror(ENOTDIR));
1374                 return(AKLOG_BADPATH);
1375             }
1376         }
1377     }
1378
1379
1380     return(status);
1381 }
1382
1383
1384 /* Print usage message and exit */
1385 static void
1386 usage(void)
1387 {
1388     fprintf(stderr, "\nUsage: %s %s%s%s\n", progname,
1389             "[-d] [[-cell | -c] cell [-k krb_realm]] ",
1390             "[[-p | -path] pathname]\n",
1391             "    [-zsubs] [-hosts] [-noauth] [-noprdb] [-force] [-setpag] \n"
1392                 "    [-linked]"
1393 #ifndef HAVE_NO_KRB5_524
1394                 " [-524]"
1395 #endif
1396                 "\n");
1397     fprintf(stderr, "    -d gives debugging information.\n");
1398     fprintf(stderr, "    krb_realm is the kerberos realm of a cell.\n");
1399     fprintf(stderr, "    pathname is the name of a directory to which ");
1400     fprintf(stderr, "you wish to authenticate.\n");
1401     fprintf(stderr, "    -zsubs gives zephyr subscription information.\n");
1402     fprintf(stderr, "    -hosts gives host address information.\n");
1403     fprintf(stderr, "    -noauth does not attempt to get tokens.\n");
1404     fprintf(stderr, "    -noprdb means don't try to determine AFS ID.\n");
1405     fprintf(stderr, "    -force means replace identical tickets. \n");
1406     fprintf(stderr, "    -linked means if AFS node is linked, try both. \n");
1407     fprintf(stderr, "    -setpag set the AFS process authentication group.\n");
1408 #ifndef HAVE_NO_KRB5_524
1409     fprintf(stderr, "    -524 means use the 524 converter instead of V5 directly\n");
1410 #endif
1411     fprintf(stderr, "    No commandline arguments means ");
1412     fprintf(stderr, "authenticate to the local cell.\n");
1413     fprintf(stderr, "\n");
1414     exit(AKLOG_USAGE);
1415 }
1416
1417 int
1418 main(int argc, char *argv[])
1419 {
1420     krb5_context context;
1421     int status = AKLOG_SUCCESS;
1422     int i;
1423     int somethingswrong = FALSE;
1424
1425     cellinfo_t cellinfo;
1426
1427     extern char *progname;      /* Name of this program */
1428
1429     int cmode = FALSE;          /* Cellname mode */
1430     int pmode = FALSE;          /* Path name mode */
1431
1432     char realm[REALM_SZ];       /* Kerberos realm of afs server */
1433     char cell[BUFSIZ];          /* Cell to which we are authenticating */
1434     char path[MAXPATHLEN + 1];          /* Path length for path mode */
1435
1436     linked_list cells;          /* List of cells to log to */
1437     linked_list paths;          /* List of paths to log to */
1438     ll_node *cur_node;
1439     char *linkedcell;
1440     const char *config = AFSDIR_CLIENT_ETC_DIRPATH;
1441
1442     memset(&cellinfo, 0, sizeof(cellinfo));
1443
1444     memset(realm, 0, sizeof(realm));
1445     memset(cell, 0, sizeof(cell));
1446     memset(path, 0, sizeof(path));
1447
1448     ll_init(&cells);
1449     ll_init(&paths);
1450
1451     ll_init(&zsublist);
1452     ll_init(&hostlist);
1453
1454     /* Store the program name here for error messages */
1455     if ((progname = strrchr(argv[0], DIR)))
1456         progname++;
1457     else
1458         progname = argv[0];
1459
1460 #if defined(KRB5_PROG_ETYPE_NOSUPP) && !(defined(HAVE_KRB5_ENCTYPE_ENABLE) || defined(HAVE_KRB5_ALLOW_WEAK_CRYPTO))
1461     {
1462         char *filepath = NULL, *newpath = NULL;
1463 #ifndef AFS_DARWIN_ENV
1464         char *defaultpath = "/etc/krb5.conf";
1465 #else
1466         char *defaultpath = "~/Library/Preferences/edu.mit.Kerberos:/Library/Preferences/edu.mit.Kerberos";
1467 #endif
1468         filepath = getenv("KRB5_CONFIG");
1469         asprintf(&newpath, "%s:%s/krb5-weak.conf",
1470                  filepath ? filepath : defaultpath,
1471                  AFSDIR_CLIENT_ETC_DIRPATH);
1472         setenv("KRB5_CONFIG", newpath, 1);
1473 #endif
1474         krb5_init_context(&context);
1475
1476 #if defined(KRB5_PROG_ETYPE_NOSUPP) && !(defined(HAVE_KRB5_ENCTYPE_ENABLE) || defined(HAVE_KRB5_ALLOW_WEAK_CRYPTO))
1477         free(newpath);
1478         if (filepath)
1479             setenv("KRB5_CONFIG", filepath, 1);
1480         else
1481             unsetenv("KRB5_CONFIG");
1482     }
1483 #endif
1484     initialize_KTC_error_table ();
1485     initialize_U_error_table();
1486     initialize_RXK_error_table();
1487     initialize_ACFG_error_table();
1488     initialize_PT_error_table();
1489     afs_set_com_err_hook(redirect_errors);
1490
1491     /*
1492      * Enable DES enctypes, which are currently still required for AFS.
1493      * krb5_allow_weak_crypto is MIT Kerberos 1.8.  krb5_enctype_enable is
1494      * Heimdal.
1495      */
1496 #if defined(HAVE_KRB5_ENCTYPE_ENABLE)
1497     i = krb5_enctype_valid(context, ETYPE_DES_CBC_CRC);
1498     if (i)
1499         krb5_enctype_enable(context, ETYPE_DES_CBC_CRC);
1500 #elif defined(HAVE_KRB5_ALLOW_WEAK_CRYPTO)
1501     krb5_allow_weak_crypto(context, 1);
1502 #endif
1503
1504     /* Initialize list of cells to which we have authenticated */
1505     ll_init(&authedcells);
1506
1507     /* Parse commandline arguments and make list of what to do. */
1508     for (i = 1; i < argc; i++) {
1509         if (strcmp(argv[i], "-d") == 0)
1510             dflag++;
1511         else if (strcmp(argv[i], "-noauth") == 0)
1512             noauth++;
1513         else if (strcmp(argv[i], "-zsubs") == 0)
1514             zsubs++;
1515         else if (strcmp(argv[i], "-hosts") == 0)
1516             hosts++;
1517         else if (strcmp(argv[i], "-noprdb") == 0)
1518             noprdb++;
1519         else if (strcmp(argv[i], "-linked") == 0)
1520                 linked++;
1521         else if (strcmp(argv[i], "-force") == 0)
1522             force++;
1523 #ifndef HAVE_NO_KRB5_524
1524         else if (strcmp(argv[i], "-524") == 0)
1525             do524++;
1526 #endif
1527     else if (strcmp(argv[i], "-setpag") == 0)
1528             afssetpag++;
1529         else if (((strcmp(argv[i], "-cell") == 0) ||
1530                   (strcmp(argv[i], "-c") == 0)) && !pmode)
1531             if (++i < argc) {
1532                 cmode++;
1533                 strcpy(cell, argv[i]);
1534             }
1535             else
1536                 usage();
1537         else if ((strcmp(argv[i], "-keytab") == 0))
1538             if (++i < argc) {
1539                 keytab = argv[i];
1540             }
1541             else
1542                 usage();
1543         else if ((strcmp(argv[i], "-principal") == 0))
1544             if (++i < argc) {
1545                 client = argv[i];
1546             }
1547             else
1548                 usage();
1549         else if (((strcmp(argv[i], "-path") == 0) ||
1550                   (strcmp(argv[i], "-p") == 0)) && !cmode)
1551             if (++i < argc) {
1552                 pmode++;
1553                 strcpy(path, argv[i]);
1554             }
1555             else
1556                 usage();
1557         else if (strcmp(argv[i], "-config") == 0)
1558             if (++i < argc) {
1559                 config = argv[i];
1560             }
1561             else
1562                 usage();
1563         else if (argv[i][0] == '-')
1564             usage();
1565         else if (!pmode && !cmode) {
1566             if (strchr(argv[i], DIR) || (strcmp(argv[i], ".") == 0) ||
1567                 (strcmp(argv[i], "..") == 0)) {
1568                 pmode++;
1569                 strcpy(path, argv[i]);
1570             }
1571             else {
1572                 cmode++;
1573                 strcpy(cell, argv[i]);
1574             }
1575         }
1576         else
1577             usage();
1578
1579         if (cmode) {
1580             if (((i + 1) < argc) && (strcmp(argv[i + 1], "-k") == 0)) {
1581                 i+=2;
1582                 if (i < argc)
1583                     strcpy(realm, argv[i]);
1584                 else
1585                     usage();
1586             }
1587             /* Add this cell to list of cells */
1588             strcpy(cellinfo.cell, cell);
1589             strcpy(cellinfo.realm, realm);
1590             if ((cur_node = ll_add_node(&cells, ll_tail))) {
1591                 char *new_cellinfo;
1592                 if ((new_cellinfo = copy_cellinfo(&cellinfo)))
1593                     ll_add_data(cur_node, new_cellinfo);
1594                 else {
1595                     fprintf(stderr,
1596                             "%s: failure copying cellinfo.\n", progname);
1597                     exit(AKLOG_MISC);
1598                 }
1599             }
1600             else {
1601                 fprintf(stderr, "%s: failure adding cell to cells list.\n",
1602                         progname);
1603                 exit(AKLOG_MISC);
1604             }
1605             memset(&cellinfo, 0, sizeof(cellinfo));
1606             cmode = FALSE;
1607             memset(cell, 0, sizeof(cell));
1608             memset(realm, 0, sizeof(realm));
1609         }
1610         else if (pmode) {
1611             /* Add this path to list of paths */
1612             if ((cur_node = ll_add_node(&paths, ll_tail))) {
1613                 char *new_path;
1614                 if ((new_path = strdup(path)))
1615                     ll_add_data(cur_node, new_path);
1616                 else {
1617                     fprintf(stderr, "%s: failure copying path name.\n",
1618                             progname);
1619                     exit(AKLOG_MISC);
1620                 }
1621             }
1622             else {
1623                 fprintf(stderr, "%s: failure adding path to paths list.\n",
1624                         progname);
1625                 exit(AKLOG_MISC);
1626             }
1627             pmode = FALSE;
1628             memset(path, 0, sizeof(path));
1629         }
1630     }
1631
1632     /* If nothing was given, log to the local cell. */
1633     if ((cells.nelements + paths.nelements) == 0) {
1634         struct passwd *pwd;
1635
1636         status = auth_to_cell(context, config, NULL, NULL, &linkedcell);
1637
1638         /* If this cell is linked to a DCE cell, and user requested -linked,
1639          * get tokens for both. This is very useful when the AFS cell is
1640          * linked to a DFS cell and this system does not also have DFS.
1641          */
1642
1643         if (!status && linked && linkedcell != NULL) {
1644             afs_dprintf("Linked cell: %s\n", linkedcell);
1645             status = auth_to_cell(context, config, linkedcell, NULL, NULL);
1646         }
1647         if (linkedcell) {
1648             free(linkedcell);
1649             linkedcell = NULL;
1650         }
1651
1652         /*
1653          * Local hack - if the person has a file in their home
1654          * directory called ".xlog", read that for a list of
1655          * extra cells to authenticate to
1656          */
1657
1658         if ((pwd = getpwuid(getuid())) != NULL) {
1659             struct stat sbuf;
1660             FILE *f;
1661             char fcell[100], xlog_path[512];
1662
1663             strcpy(xlog_path, pwd->pw_dir);
1664             strcat(xlog_path, "/.xlog");
1665
1666             if ((stat(xlog_path, &sbuf) == 0) &&
1667                 ((f = fopen(xlog_path, "r")) != NULL)) {
1668
1669                 afs_dprintf("Reading %s for cells to authenticate to.\n",
1670                         xlog_path);
1671
1672                 while (fgets(fcell, 100, f) != NULL) {
1673                     int auth_status;
1674
1675                     fcell[strlen(fcell) - 1] = '\0';
1676
1677                     afs_dprintf("Found cell %s in %s.\n", fcell, xlog_path);
1678
1679                     auth_status = auth_to_cell(context, config, fcell, NULL, NULL);
1680                     if (status == AKLOG_SUCCESS)
1681                         status = auth_status;
1682                     else
1683                         status = AKLOG_SOMETHINGSWRONG;
1684                 }
1685             }
1686         }
1687     }
1688     else {
1689         /* Log to all cells in the cells list first */
1690         for (cur_node = cells.first; cur_node; cur_node = cur_node->next) {
1691             memcpy((char *)&cellinfo, cur_node->data, sizeof(cellinfo));
1692             status = auth_to_cell(context, config, cellinfo.cell,
1693                                   cellinfo.realm, &linkedcell);
1694             if (status) {
1695                 somethingswrong++;
1696             } else {
1697                 if (linked && linkedcell != NULL) {
1698                     afs_dprintf("Linked cell: %s\n", linkedcell);
1699                     status = auth_to_cell(context, config, linkedcell,
1700                                           cellinfo.realm, NULL);
1701                     if (status)
1702                         somethingswrong++;
1703                 }
1704                 if (linkedcell != NULL) {
1705                     free(linkedcell);
1706                     linkedcell = NULL;
1707                 }
1708             }
1709         }
1710
1711         /* Then, log to all paths in the paths list */
1712         for (cur_node = paths.first; cur_node; cur_node = cur_node->next) {
1713             status = auth_to_path(context, config, cur_node->data);
1714             if (status)
1715                 somethingswrong++;
1716         }
1717
1718         /*
1719          * If only one thing was logged to, we'll return the status
1720          * of the single call.  Otherwise, we'll return a generic
1721          * something failed status.
1722          */
1723         if (somethingswrong && ((cells.nelements + paths.nelements) > 1))
1724             status = AKLOG_SOMETHINGSWRONG;
1725     }
1726
1727     /* If we are keeping track of zephyr subscriptions, print them. */
1728     if (zsubs)
1729         for (cur_node = zsublist.first; cur_node; cur_node = cur_node->next) {
1730             printf("zsub: %s\n", cur_node->data);
1731         }
1732
1733     /* If we are keeping track of host information, print it. */
1734     if (hosts)
1735         for (cur_node = hostlist.first; cur_node; cur_node = cur_node->next) {
1736             printf("host: %s\n", cur_node->data);
1737         }
1738
1739     exit(status);
1740 }
1741
1742 static int
1743 isdir(char *path, unsigned char *val)
1744 {
1745     struct stat statbuf;
1746
1747     if (lstat(path, &statbuf) < 0)
1748         return (-1);
1749     else {
1750         if ((statbuf.st_mode & S_IFMT) == S_IFDIR)
1751             *val = TRUE;
1752         else
1753             *val = FALSE;
1754         return (0);
1755     }
1756 }
1757
1758 static krb5_error_code
1759 get_credv5_akimpersonate(krb5_context context,
1760                          char* keytab,
1761                          krb5_principal service_principal,
1762                          krb5_principal client_principal,
1763                          time_t starttime,
1764                          time_t endtime,
1765                          int *allowed_enctypes,
1766                          int *paddress,
1767                          krb5_creds** out_creds /* out */ )
1768 {
1769 #if defined(USING_HEIMDAL) || (defined(HAVE_ENCODE_KRB5_ENC_TKT) && defined(HAVE_ENCODE_KRB5_TICKET) && defined(HAVE_KRB5_C_ENCRYPT))
1770     krb5_error_code code;
1771     krb5_keytab kt = 0;
1772     krb5_kt_cursor cursor[1];
1773     krb5_keytab_entry entry[1];
1774     krb5_ccache cc = 0;
1775     krb5_creds *creds = 0;
1776     krb5_enctype enctype;
1777     krb5_kvno kvno;
1778     krb5_keyblock session_key[1];
1779 #if USING_HEIMDAL
1780     Ticket ticket_reply[1];
1781     EncTicketPart enc_tkt_reply[1];
1782     krb5_address address[30];
1783     krb5_addresses faddr[1];
1784     unsigned int temp_vno[1];
1785     time_t temp_time[2];
1786 #else
1787     krb5_ticket ticket_reply[1];
1788     krb5_enc_tkt_part enc_tkt_reply[1];
1789     krb5_address address[30], *faddr[30];
1790     krb5_data * temp;
1791 #endif
1792     int i;
1793     static int any_enctype[] = {0};
1794     *out_creds = 0;
1795     if (!(creds = malloc(sizeof *creds))) {
1796         code = ENOMEM;
1797         goto cleanup;
1798     }
1799     if (!allowed_enctypes)
1800         allowed_enctypes = any_enctype;
1801
1802     cc = 0;
1803     enctype = 0; /* AKIMPERSONATE_IGNORE_ENCTYPE */
1804     kvno = 0; /* AKIMPERSONATE_IGNORE_VNO */
1805     memset((char*)creds, 0, sizeof *creds);
1806     memset((char*)entry, 0, sizeof *entry);
1807     memset((char*)session_key, 0, sizeof *session_key);
1808     memset((char*)ticket_reply, 0, sizeof *ticket_reply);
1809     memset((char*)enc_tkt_reply, 0, sizeof *enc_tkt_reply);
1810     code = krb5_kt_resolve(context, keytab, &kt);
1811     if (code) {
1812         if (keytab)
1813             afs_com_err(progname, code, "while resolving keytab %s", keytab);
1814         else
1815             afs_com_err(progname, code, "while resolving default keytab");
1816         goto cleanup;
1817     }
1818
1819     if (service_principal) {
1820         for (i = 0; (enctype = allowed_enctypes[i]) || !i; ++i) {
1821             code = krb5_kt_get_entry(context,
1822                                      kt,
1823                                      service_principal,
1824                                      kvno,
1825                                      enctype,
1826                                      entry);
1827             if (!code) {
1828                 if (allowed_enctypes[i])
1829                     deref_keyblock_enctype(session_key) = allowed_enctypes[i];
1830                 break;
1831             }
1832         }
1833         if (code) {
1834             afs_com_err(progname, code,"while scanning keytab entries");
1835             goto cleanup;
1836         }
1837     } else {
1838         krb5_keytab_entry new[1];
1839         int best = -1;
1840         memset(new, 0, sizeof *new);
1841         if ((code == krb5_kt_start_seq_get(context, kt, cursor))) {
1842             afs_com_err(progname, code, "while starting keytab scan");
1843             goto cleanup;
1844         }
1845         while (!(code = krb5_kt_next_entry(context, kt, new, cursor))) {
1846             for (i = 0;
1847                     allowed_enctypes[i] && allowed_enctypes[i]
1848                      != deref_entry_enctype(new); ++i)
1849                 ;
1850             if ((!i || allowed_enctypes[i]) &&
1851                 (best < 0 || best > i)) {
1852                 krb5_free_keytab_entry_contents(context, entry);
1853                 *entry = *new;
1854                 memset(new, 0, sizeof *new);
1855             } else krb5_free_keytab_entry_contents(context, new);
1856         }
1857         if ((i = krb5_kt_end_seq_get(context, kt, cursor))) {
1858             afs_com_err(progname, i, "while ending keytab scan");
1859             code = i;
1860             goto cleanup;
1861         }
1862         if (best < 0) {
1863             afs_com_err(progname, code, "while scanning keytab");
1864             goto cleanup;
1865         }
1866         deref_keyblock_enctype(session_key) = deref_entry_enctype(entry);
1867     }
1868
1869     /* Make Ticket */
1870
1871 #if USING_HEIMDAL
1872     if ((code = krb5_generate_random_keyblock(context,
1873                                               deref_keyblock_enctype(session_key), session_key))) {
1874         afs_com_err(progname, code, "while making session key");
1875         goto cleanup;
1876     }
1877     enc_tkt_reply->flags.initial = 1;
1878     enc_tkt_reply->transited.tr_type = DOMAIN_X500_COMPRESS;
1879     enc_tkt_reply->cname = client_principal->name;
1880     enc_tkt_reply->crealm = client_principal->realm;
1881     enc_tkt_reply->key = *session_key;
1882     {
1883         static krb5_data empty_string;
1884         enc_tkt_reply->transited.contents = empty_string;
1885     }
1886     enc_tkt_reply->authtime = starttime;
1887     enc_tkt_reply->starttime = temp_time;
1888     *enc_tkt_reply->starttime = starttime;
1889 #if 0
1890     enc_tkt_reply->renew_till = temp_time + 1;
1891     *enc_tkt_reply->renew_till = endtime;
1892 #endif
1893     enc_tkt_reply->endtime = endtime;
1894 #else
1895     if ((code = krb5_c_make_random_key(context,
1896                                        deref_keyblock_enctype(session_key), session_key))) {
1897         afs_com_err(progname, code, "while making session key");
1898         goto cleanup;
1899     }
1900     enc_tkt_reply->magic = KV5M_ENC_TKT_PART;
1901 #define DATACAST        (unsigned char *)
1902     enc_tkt_reply->flags |= TKT_FLG_INITIAL;
1903     enc_tkt_reply->transited.tr_type = KRB5_DOMAIN_X500_COMPRESS;
1904     enc_tkt_reply->session = session_key;
1905     enc_tkt_reply->client = client_principal;
1906     {
1907         static krb5_data empty_string;
1908         enc_tkt_reply->transited.tr_contents = empty_string;
1909     }
1910     enc_tkt_reply->times.authtime = starttime;
1911     enc_tkt_reply->times.starttime = starttime; /* krb524init needs this */
1912     enc_tkt_reply->times.endtime = endtime;
1913 #endif  /* USING_HEIMDAL */
1914     /* NB:  We will discard address for now--ignoring caddr field
1915        in any case.  MIT branch does what it always did. */
1916
1917     if (paddress && *paddress) {
1918         deref_enc_tkt_addrs(enc_tkt_reply) = faddr;
1919 #if USING_HEIMDAL
1920         faddr->len = 0;
1921         faddr->val = address;
1922 #endif
1923         for (i = 0; paddress[i]; ++i) {
1924 #if USING_HEIMDAL
1925             address[i].addr_type = KRB5_ADDRESS_INET;
1926             address[i].address.data = (void*)(paddress+i);
1927             address[i].address.length = sizeof(paddress[i]);
1928 #else
1929 #if !USING_SSL
1930             address[i].magic = KV5M_ADDRESS;
1931             address[i].addrtype = ADDRTYPE_INET;
1932 #else
1933             address[i].addrtype = AF_INET;
1934 #endif
1935             address[i].contents = (void*)(paddress+i);
1936             address[i].length = sizeof(int);
1937             faddr[i] = address+i;
1938 #endif
1939         }
1940 #if USING_HEIMDAL
1941         faddr->len = i;
1942 #else
1943         faddr[i] = 0;
1944 #endif
1945     }
1946
1947 #if USING_HEIMDAL
1948     ticket_reply->sname = service_principal->name;
1949     ticket_reply->realm = service_principal->realm;
1950
1951     { /* crypto block */
1952         krb5_crypto crypto = 0;
1953         unsigned char *buf = 0;
1954         size_t buf_size, buf_len;
1955         char *what;
1956
1957         ASN1_MALLOC_ENCODE(EncTicketPart, buf, buf_size,
1958                            enc_tkt_reply, &buf_len, code);
1959         if(code) {
1960             afs_com_err(progname, code, "while encoding ticket");
1961             goto cleanup;
1962         }
1963
1964         if(buf_len != buf_size) {
1965             afs_com_err(progname, code,
1966                     "%u != %u while encoding ticket (internal ASN.1 encoder error",
1967                     (unsigned int)buf_len, (unsigned int)buf_size);
1968             goto cleanup;
1969         }
1970         what = "krb5_crypto_init";
1971         code = krb5_crypto_init(context,
1972                                 &deref_entry_keyblock(entry),
1973                                 deref_entry_enctype(entry),
1974                                 &crypto);
1975         if(!code) {
1976             what = "krb5_encrypt";
1977             code = krb5_encrypt_EncryptedData(context, crypto, KRB5_KU_TICKET,
1978                                               buf, buf_len, entry->vno, &(ticket_reply->enc_part));
1979         }
1980         if (buf) free(buf);
1981         if (crypto) krb5_crypto_destroy(context, crypto);
1982         if(code) {
1983             afs_com_err(progname, code, "while %s", what);
1984             goto cleanup;
1985         }
1986     } /* crypto block */
1987     ticket_reply->enc_part.etype = deref_entry_enctype(entry);
1988     ticket_reply->enc_part.kvno = (void *)temp_vno;
1989     *ticket_reply->enc_part.kvno = entry->vno;
1990     ticket_reply->tkt_vno = 5;
1991 #else
1992     ticket_reply->server = service_principal;
1993     ticket_reply->enc_part2 = enc_tkt_reply;
1994     if ((code = krb5_encrypt_tkt_part(context, &deref_entry_keyblock(entry), ticket_reply))) {
1995         afs_com_err(progname, code, "while making ticket");
1996         goto cleanup;
1997     }
1998     ticket_reply->enc_part.kvno = entry->vno;
1999 #endif
2000
2001     /* Construct Creds */
2002
2003     if ((code = krb5_copy_principal(context, service_principal,
2004                                     &creds->server))) {
2005         afs_com_err(progname, code, "while copying service principal");
2006         goto cleanup;
2007     }
2008     if ((code = krb5_copy_principal(context, client_principal,
2009                                     &creds->client))) {
2010         afs_com_err(progname, code, "while copying client principal");
2011         goto cleanup;
2012     }
2013     if ((code = krb5_copy_keyblock_contents(context, session_key,
2014                                             &deref_session_key(creds)))) {
2015         afs_com_err(progname, code, "while copying session key");
2016         goto cleanup;
2017     }
2018
2019 #if USING_HEIMDAL
2020     creds->times.authtime = enc_tkt_reply->authtime;
2021     creds->times.starttime = *(enc_tkt_reply->starttime);
2022     creds->times.endtime = enc_tkt_reply->endtime;
2023     creds->times.renew_till = 0; /* *(enc_tkt_reply->renew_till) */
2024     creds->flags.b = enc_tkt_reply->flags;
2025 #else
2026     creds->times = enc_tkt_reply->times;
2027     creds->ticket_flags = enc_tkt_reply->flags;
2028 #endif
2029     if (!deref_enc_tkt_addrs(enc_tkt_reply))
2030         ;
2031     else if ((code = krb5_copy_addresses(context,
2032                                          deref_enc_tkt_addrs(enc_tkt_reply), &creds->addresses))) {
2033         afs_com_err(progname, code, "while copying addresses");
2034         goto cleanup;
2035     }
2036
2037 #if USING_HEIMDAL
2038     {
2039         size_t creds_tkt_len;
2040         ASN1_MALLOC_ENCODE(Ticket, creds->ticket.data, creds->ticket.length,
2041                            ticket_reply, &creds_tkt_len, code);
2042         if(code) {
2043             afs_com_err(progname, code, "while encoding ticket");
2044             goto cleanup;
2045         }
2046     }
2047 #else
2048     if ((code = encode_krb5_ticket(ticket_reply, &temp))) {
2049         afs_com_err(progname, code, "while encoding ticket");
2050         goto cleanup;
2051     }
2052     creds->ticket = *temp;
2053     free(temp);
2054 #endif
2055     /* return creds */
2056     *out_creds = creds;
2057     creds = 0;
2058 cleanup:
2059     if (deref_enc_data(&ticket_reply->enc_part))
2060         free(deref_enc_data(&ticket_reply->enc_part));
2061     krb5_free_keytab_entry_contents(context, entry);
2062     if (client_principal)
2063         krb5_free_principal(context, client_principal);
2064     if (service_principal)
2065         krb5_free_principal(context, service_principal);
2066     if (cc)
2067         krb5_cc_close(context, cc);
2068     if (kt)
2069         krb5_kt_close(context, kt);
2070     if (creds) krb5_free_creds(context, creds);
2071     krb5_free_keyblock_contents(context, session_key);
2072     return code;
2073 #else
2074     return -1;
2075 #endif
2076 }
2077
2078
2079 static krb5_error_code
2080 get_credv5(krb5_context context, char *name, char *inst, char *realm,
2081            krb5_creds **creds)
2082 {
2083     krb5_creds increds;
2084     krb5_error_code r;
2085     static krb5_principal client_principal = 0;
2086
2087     afs_dprintf("Getting tickets: %s%s%s@%s\n", name,
2088             (inst && inst[0]) ? "/" : "", inst ? inst : "", realm);
2089
2090     memset(&increds, 0, sizeof(increds));
2091 /* ANL - instance may be ptr to a null string. Pass null then */
2092     if ((r = krb5_build_principal(context, &increds.server,
2093                                   strlen(realm), realm,
2094                                   name,
2095                                   (inst && strlen(inst)) ? inst : (void *) NULL,
2096                                   (void *) NULL))) {
2097         return r;
2098     }
2099
2100
2101     if (!_krb425_ccache) {
2102         r = krb5_cc_default(context, &_krb425_ccache);
2103         if (r)
2104             return r;
2105     }
2106     if (!client_principal) {
2107         if (client) {
2108             r = krb5_parse_name(context, client,  &client_principal);
2109         } else {
2110             r = krb5_cc_get_principal(context, _krb425_ccache, &client_principal);
2111         }
2112         if (r)
2113             return r;
2114     }
2115
2116     increds.client = client_principal;
2117     increds.times.endtime = 0;
2118     /* Ask for DES since that is what V4 understands */
2119     get_creds_enctype((&increds)) = ENCTYPE_DES_CBC_CRC;
2120
2121     if (keytab) {
2122         int allowed_enctypes[] = {
2123             ENCTYPE_DES_CBC_CRC, 0
2124         };
2125
2126         r = get_credv5_akimpersonate(context,
2127                                      keytab,
2128                                      increds.server,
2129                                      increds.client,
2130                                      300, ((~0U)>>1),
2131                                      allowed_enctypes,
2132                                      0 /* paddress */,
2133                                      creds /* out */);
2134     } else {
2135         r = krb5_get_credentials(context, 0, _krb425_ccache, &increds, creds);
2136     }
2137     return r;
2138 }
2139
2140
2141 static int
2142 get_user_realm(krb5_context context, char **realm)
2143 {
2144     static krb5_principal client_principal = 0;
2145     krb5_error_code r = 0;
2146
2147     *realm = NULL;
2148
2149     if (!_krb425_ccache) {
2150         r = krb5_cc_default(context, &_krb425_ccache);
2151         if (r)
2152             return r;
2153     }
2154     if (!client_principal) {
2155         if (client) {
2156             r = krb5_parse_name(context, client,  &client_principal);
2157         } else {
2158             r = krb5_cc_get_principal(context, _krb425_ccache, &client_principal);
2159         }
2160         if (r)
2161             return r;
2162     }
2163
2164     *realm = extract_realm(context, client_principal);
2165     if (*realm == NULL)
2166         return ENOMEM;
2167
2168     return(r);
2169 }