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