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