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