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